SQL Essential Training
SQL Statement:
SELECT * FROM Countries WHERE Continent == 'Europe';
INSERT
INSERT INTO Customer (name, city, state)
Values (‘Jimi Hendrix’, ‘Renton’, ‘WA’);
INSERT INTO customer (name, address, city, state , zip)
VALUES ('Fred Flintstone', '123 Cobblestone', 'Bedrock', 'CA', '91234');
INSERT INTO customer (name, city, state )
VALUES ('Fred Flintstone', 'Bedrock', 'CA');
Update
UPDATE Customer
SET
Address = ‘123 Music Avenue’
Zip = ‘98056’
WHERE id = 5;
Delete
DELETE FROM Customer WHERE id = 4;
SQL Statement
SELECT * FROM Table;
Not case sensitive
Comment: -- this is a comment or /* this is a comment*/
SQL Clauses
SELECT * FROM Album WHERE Label = ‘Columbia’;
SQL Functions
SELECT Count(*) FROM Album WHERE Label = ‘Columbia’;
SELECT Count(*) FROM Country WHERE Population > 100000 AND Continent = 'Europe';
SELECT Count(LifeExpectancy) FROM Country;
SQL Expressions
SELECT Name, Populations/10000 AS PopMM
FROM Country
Where Populations >= 100000
ORDER BY Population DESC;
LIMIT 5
OFFSET 5; //offset gets the second 5 rows
Creating a Table
CREATE TABLE test(
a INTEGER, - Schema
b TEXT
);
INSERT INTO test VALUES ( 1, 'a');
INSERT INTO test VALUES ( 2, 'b');
INSERT INTO test VALUES ( 3, 'c');
Deleting a Table
DROP TABLE test;
DROP TABLE IF EXISTS test;
Inserting Rows
INSERT INTO test VALUES ( 1, 'a', 'b');
INSERT INTO test (b, c) VALUES ( 'a', 'b'); - Do not need to insert into all columns
INSERT INTO test DEFAULT VALUES; - Default values are NULL
INSERT INTO test (a, b, c) SELECT id, name, description from item; - Selects from another table and
inserts
The Null Value
SELECT * FROM test WHERE a IS NULL;
SELECT * FROM test WHERE a IS NOT NULL;
CREATE TABLE test(
a INTEGER NOT NULL.
b INTERGER NOT NULL,
c TEXT);
Constraining columns
CREATE TABLE test ( a TEXT, b TEXT, c TEXT DEFAULT 'panda'); - If we do not specify value, uses default
INSERT INTO test (a,b) VALUES ('one', 'two');
CREATE TABLE test ( a TEXT UNIQUE, b TEXT, c TEXT DEFAULT 'panda'); - need unique values for columns
a
CREATE TABLE test ( a TEXT UNIQUE NOT NULL, b TEXT, c TEXT DEFAULT 'panda'); - need unique values
for columns a, SO YOU CANNOT HAVE DUPLICATE VALUES INCLUDING NULL VALUES
Changing a schema
ALTER TABLE test ADD d TEXT; - adding column d to already created table
ALTER TABLE test ADD e TEXT DEFAULT ‘panda’ – instead of adding column with all NULL values, adds
default values instead
ID columns
CREATE TABLE test (
Id INTEGER PRIMARY KEY, - WILL POPULATE ITSELF
a INTEGER,
b TEXT);
Filtering Data
SELECT Name, Continent, Population FROM Country
WHERE Population < 100000 OR Population IS NULL ORDER BY Population DESC;
SELECT Name, Continent, Population FROM Country
WHERE Name LIKE ‘%island%’ ORDER BY Name; - any word that had island in it. Taking out all
% means the whole world has only island in it. Can change to %island meaning that it will collect all the
words that ends in the word island
SELECT Name, Continent, Population FROM Country
WHERE Name LIKE ‘_a%’ ORDER BY Name; - matches with words that have a as the second
letter and anything after it
SELECT Name, Continent, Population FROM Country
WHERE Continent IN (‘Europe’, ‘Asia’);
Removing Duplicates
SELECT DISTINCT Continent FROM Country; - List of all unique values
SELECT DISTINCT Name, Continent FROM Country; - List of unique combinations
Ordering Output
SELECT Name FROM Country ORDER BY Name DESC;
SELECT Name FROM Country ORDER BY Name ASC;
SELECT Name FROM Country ORDER BY Name, Continent; - Order by name first and then
continent
SELECT Name, Continent, Region FROM Country ORDER BY Continent DESC, Region, Name ASC;
Conditional Expressions
CREATE TABLE booltest(a int, b int);
INSERT INTO booltest VALUES (1,0);
SELECT
CASE WHEN a THEN ‘true’ ELSE ‘false’ END as boolA; -testing whether true or false
CASE WHEN b THEN ‘TRUE’ ELSE ‘false’ END as boolB;
FROM booltest;
SELECT
CASE WHEN 1 THEN ‘true’ ELSE ‘false’ END as boolA; -testing whether equal to specific value
CASE WHEN 1 THEN ‘TRUE’ ELSE ‘false’ END as boolB;
FROM booltest;
Join
Inner Join
Left Outer Join
Right Out Join
Full Outer Join
SELECT l.description AS left, r.description AS right
FROM left AS l
JOIN right AS r ON l.id = r.id;
SELECT c.name AS Cust, c.zip, i.name AS Item, i.description, s.quantity AS Quan, s.price AS price
FROM sale AS s
JOIN item AS i ON s.item_it= i.id
JOIN customer AS c ON s.customer_id = c.id
ORDER BY Cust, Item;
Strings
Literal String
SELECT ‘a literal SQL string’
Single quote in string
SELECT ‘Here’’s a single quote mark’;
Concatenation in standard SQL
SELECT ‘This’ || ‘&’ || ‘that’;
String functions
SUBSTR (string, start, length);
LENGTH (string); - provides length of string
TRIM (string, character to remove); -removes character from both ends of string
LTRIM (string, character to remove); - removes character from left ends of string
RTRIM (string, character to remove);
UPPER (string);
LOWER (string);
SELECT Name, LENGTH(Name) AS Len
FROM City
ORDER BY Len desc, Name;
SELECT ‘StRing’ = ‘string’; - returns 0 aka false as they are not the same
SELECT LOWER(‘StRing’) = LOWER(‘string’); - returns true
Numeric Types
INTEGER (precision)
DECIMAL (precision, scale)
MONEY (precision, scale)
REAL (precision)
FLOAT (precisions)
What type is that value?
SELECT TYPEOF (1 + 1) -Integer
SELECT TYPEOF (1 + 1.0) -Real
SELECT TYPEOF (‘panda’ + ‘koala’) -Integer
Integer Division
SELECT 1 / 2; – 0 Integer
SELECT 1.0 / 2; – 0.5 Real
SELECT CAST (1 AS REAL) / 2;
SELECT 1 % 2 – 5 Integer
Rounding Numbers
SELECT ROUND (2.555555) – 3
SELECT ROUND (2.555555, 3) – 2.556
Dates and Times
Standard SQL Format in UTC
Do not have specific types
DATE
TIME
DATETIME
YEAR
INTERVAL
SELECT DATETIME(‘now’)- provides timestamp
SELECT DATE(‘now’)
SELECT TIME(‘now)
SELECT DATETIME (‘now’, ‘+3 hours’, ‘+27 minutes’, ‘-1day’, ‘+3 years’)
What are aggregates?
SELECT Region, COUNT (*) AS Count
FROM Country
GROUP BY Region
ORDER BY Count DESC, Region
SELECT a.title AS Album, COUNT(t.track_number) as Tracks
FROM track AS t
JOIN album AS a ON a.id = t.album_id
WHERE a.artist = ‘The Beatles’ – filtering for non-aggregate data
GROUP BY a.id
HAVING Tracks >= 10 – filtering for aggregates data
ORDER BY Tracks DESC, Album;
Using aggregate functions
SELECT AVG(Populations) FROM Country GROUP BY Region;
Aggregating DISTINCT values
SELECT COUNT (DISTINCT HeadOfState) FROM Country;
What are transactions?
BEGIN TRANSACTION
INSERT INTO table_1
INSERT INTO table_2
SELECT INTO table_2
INSERT INTO table_3
END TRANSACTION
Data Integrity
BEGIN TRANSACTION;
INSERT INTO widgetSales (inv_id, quan, price ) VALUES (1, 5, 500);
UPDATE widgetInventory SET onhand = ( onhand – 5 ) WHERE id = 1; - decreasing onhand;
column by 5
END TRANSACTION;
BEGIN TRANSACTION;
INSERT INTO widgetInventory ( description, onhand) VALUES ( ‘toy’, 25);
ROLLBACK; -realize that transaction needs to be aborted so you use rollback to previous state
Performance – transactions use to increase performance
Automating data with triggers
CREATE TRIGGER newWidgetSale AFTER INSERT ON widgetSale
BEGIN
UPDATE widgetCustomer SET last_order_id = NEW.id WHERE widgetCustomer.id = NEW.customer_id; -
NEW refers to new row that is inserted
END
Preventing updates
CREATE TRIGGER updateWidgetSale BERFORE UPDATE ON widgetSale – PREVENT UPDATE TO ROW
THAT IS ALREADY RECONCILED
BEGIN
SELECT RAISE(ROLLBACK, ‘cannot update “table widgetSale”’) FROM widgetSale
WHERE id = NEW.id AND reconciled = 1;
END;
Creating a subselect
SELECT co.Name, ss.CCode FROM (
SELECT SUBSTR(a, 1,2 ) AS State, SUBSTR(a, 3) AS SCode,
SUBSTR(b,1,2) AS Country, SUBSTR(b, 3) AS CCode FROM t
) AS ss
JOIN Country AS co
ON co.Code2 = ss.Country;
Creating a view
CREATE VIEW trackView AS
Query here..
DROP VIEW IF EXISTS trackView;