Crash course in SQL
www.skewcode.com
MySQL - Installation
DOWNLOAD
ā—‹ https://dev.mysql.com/downloads
ā–  MySQL Community Server
ā–  MySQL Shell
ā–  [OPTIONAL] MySQL Workbench
ā—‹ https://dev.mysql.com/doc/index-other.html
ā–  Example databases -> world database
Data Types
Data types
ā— Numeric types (INT, DECIMAL, FLOAT, DOUBLE, BIT)
ā— Date & Time types (DATE, TIME, DATETIME, TIMESTAMP)
ā— String types (CHAR, VARCHAR, TEXT, ENUM)
Data Definition Statements
Database related operations
List all databases SHOW DATABASES;
Create a new database. CREATE DATABASE mydb1;
Create a new database (if not existing). CREATE DATABASE IF NOT EXISTS mydb1;
Use an existing database. USE mydb1;
List current database. SELECT DATABASE();
Delete existing database. DROP DATABASE mydb1;
Delete existing database (if existing). DROP DATABASE IF EXISTS mydb1;
Data Definition Statements
Table related operations
List all tables in current database SHOW TABLES;
See structure of a specific table. DESCRIBE mytable1;
Create a new table (if not existing). CREATE TABLE IF NOT EXISTS mytable1
(
serialnum INT,
name VARCHAR(20),
location ENUM(ā€˜BLR’, ā€˜BOM’, ā€˜DEL’)
);
Delete existing table (if existing). DROP TABLE IF EXISTS mytable1;
Data Definition Statements
Table related operations
Adding columns. ALTER TABLE mytable1
ADD COLUMN firstname varchar(25),
ADD COLUMN lastname varchar(40);
Deleting columns. ALTER TABLE mytable1
DROP COLUMN firstname,
DROP COLUMN lastname;
Modifying columns. ALTER TABLE mytable1
MODIFY COLUMN firstname varchar(25),
MODIFY COLUMN lastname varchar(40);
Data Definition Statements
Constraints
NOT NULL CREATE TABLE mytable1 (col1 INT NOT NULL);
PRIMARY KEY CREATE TABLE mytable1 (col1 INT, PRIMARY KEY (col1));
UNIQUE CREATE TABLE mytable1 (col1 INT UNIQUE);
FOREIGN KEY CREATE TABLE mytable1
(
col1 INT, FOREIGN KEY(col1) REFERENCES mytable2(mycol)
);
DEFAULT CREATE TABLE mytable1 (col1 INT DEFAULT 100);
Data Manipulation Statements
Adding, deleting and updating data (rows)
Add a new row (data in all
columns).
INSERT INTO mytable1
VALUES (ā€˜10’, ā€˜mithun’, ā€˜shanbhag’);
Add a new row (data in
specific columns).
INSERT INTO mytable1 (firstname, lastname)
VALUES (ā€˜mithun’, ā€˜shanbhag’);
Update row(s). UPDATE mytable1
SET firstname = ā€˜sachin’, lastname = ā€˜tendulkar’
WHERE serialnum = 101;
Delete row(s). DELETE FROM mytable1
WHERE firstname = ā€˜mithun’;
Delete all row(s). DELETE * FROM mytable1;
Data Query Statements
ā— Data Query Statements
ā—‹ Filtering Operations (WHERE)
ā—‹ Sorting Operations (ORDER BY)
ā—‹ Set Operations (DISTINCT, UNION, UNION ALL)
ā—‹ Paging Operations (LIMIT)
ā—‹ Aliasing Operations (AS)
ā—‹ Aggregation Operations (MIN, MAX, AVERAGE, SUM, COUNT)
ā—‹ Grouping Operations (GROUP BY)
ā—‹ Join Operations (JOIN)
Data Query Statements
Filtering Operations (WHERE)
Extract cities in USA. SELECT *
FROM city
WHERE countrycode = ’usa’;
Extract cities in USA with
population greater than
1,000,000.
SELECT *
FROM city
WHERE countrycode = ’usa’ AND population >
1000000;
Extract cities in USA or
cities with population
greater than 1,000,000.
SELECT *
FROM city
WHERE countrycode = ā€˜usa’ OR population > 1000000;
Data Query Statements
Filtering Operations (WHERE)
Extract countries starting
with ā€˜B’.
SELECT *
FROM country
WHERE name LIKE ’b%’;
Extract countries starting
with ā€˜B’ and ending with ā€˜a’.
SELECT *
FROM country
WHERE name LIKE ’b%a’;
Extract countries which
have 5 letters in their
name.
SELECT *
FROM country
WHERE name LIKE ’_____’;
Data Query Statements
Filtering Operations (WHERE)
Extract countries with no
head of state.
SELECT *
FROM country
WHERE headofstate IS NULL;
Extract countries which
have heads of state.
SELECT *
FROM country
WHERE headofstate IS NOT NULL;
Extract countries
beginning from letter ā€˜W’
onwards.
SELECT *
FROM country
WHERE name > ’w’;
Extract countries with
population between
10,000 and 20,000.
SELECT *
FROM country
WHERE population BETWEEN 10000 AND 20000;
Data Query Statements
Sorting Operations (ORDER BY)
Sort countries by name. SELECT *
FROM country
ORDER BY name;
Sort countries by population (descending). SELECT *
FROM country
ORDER BY population DESC;
Sort countries by continent, then by
population (descending).
SELECT *
FROM country
ORDER BY continent, population DESC;
Data Query Statements
Set Operations (DISTINCT)
Extract unique continent names SELECT DISTINCT continent
FROM country;
Extract unique countrycode and district
combinations
SELECT DISTINCT countrycode, district
FROM city;
Data Query Statements
Set Operations (UNION)
ā— Combines the result-set of two or more SELECT statements.
ā— Each SELECT statement must have the same number of columns, with ā€˜similar’ data types and in the
same order.
ā— UNION supports only ā€˜distinct’ values, however UNION ALL allows duplicates.
Combine the list of country codes from
the ā€˜city’ and ā€˜countrylanguage’ tables.
SELECT countrycode FROM city
UNION
SELECT countrycode FROM countrylanguage
ORDER BY countrycode;
Data Query Statements
Paging Operations (LIMIT)
ā— Constrain the number of rows returned in result set.
Extract top 5 countries, sorted by
population.
SELECT *
FROM country
ORDER BY population DESC
LIMIT 5;
Extract countries 6 to 10, sorted by
population.
SELECT *
FROM country
ORDER BY population DESC
LIMIT 5, 5;
Data Query Statements
Aliasing Operations (AS)
ā— Gives a table (or column) a temporary, readable name (alias).
ā— The alias exists only for the duration of the query.
Aliasing a column name. SELECT name AS cityname, population
FROM country
WHERE cityname = ā€˜new york’;
Aliasing a table name. SELECT name, population
FROM country as c
WHERE c.name = ā€˜new york’;
Data Query Statements
Aggregation Operations (MIN, MAX, AVG, SUM, COUNT)
Least population. SELECT MIN(population)
FROM country;
Most population. SELECT MAX(population)
FROM country;
Average population. SELECT AVG(population)
FROM country;
Total population. SELECT SUM(population)
FROM country;
Total number of countries. SELECT COUNT(name)
FROM country;
Data Query Statements
Grouping Operations (GROUP BY)
ā— Groups the result set using a ā€˜key’.
ā— The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG).
Find number of countries in each continent. SELECT continent, count(name)
FROM country
GROUP BY continent;
Group Swedish districts by total
population.
SELECT district, sum(population)
FROM city
WHERE countrycode = ā€˜swe’
GROUP BY district;
Data Query Statements
Join Operations
INNER JOIN LEFT OUTER
JOIN
RIGHT OUTER
JOIN
FULL OUTER
JOIN
Data Query Statements
Inner Join
Display continent
information for cities.
SELECT id, city.name, countrycode, district, continent
FROM city
INNER JOIN country ON city.CountryCode = country.code;
References
ā— https://dev.mysql.com/doc/refman/5.7/en/
ā— https://www.w3schools.com/sql/default.asp

Crash course in sql

  • 1.
    Crash course inSQL www.skewcode.com
  • 2.
    MySQL - Installation DOWNLOAD ā—‹https://dev.mysql.com/downloads ā–  MySQL Community Server ā–  MySQL Shell ā–  [OPTIONAL] MySQL Workbench ā—‹ https://dev.mysql.com/doc/index-other.html ā–  Example databases -> world database
  • 3.
    Data Types Data types ā—Numeric types (INT, DECIMAL, FLOAT, DOUBLE, BIT) ā— Date & Time types (DATE, TIME, DATETIME, TIMESTAMP) ā— String types (CHAR, VARCHAR, TEXT, ENUM)
  • 4.
    Data Definition Statements Databaserelated operations List all databases SHOW DATABASES; Create a new database. CREATE DATABASE mydb1; Create a new database (if not existing). CREATE DATABASE IF NOT EXISTS mydb1; Use an existing database. USE mydb1; List current database. SELECT DATABASE(); Delete existing database. DROP DATABASE mydb1; Delete existing database (if existing). DROP DATABASE IF EXISTS mydb1;
  • 5.
    Data Definition Statements Tablerelated operations List all tables in current database SHOW TABLES; See structure of a specific table. DESCRIBE mytable1; Create a new table (if not existing). CREATE TABLE IF NOT EXISTS mytable1 ( serialnum INT, name VARCHAR(20), location ENUM(ā€˜BLR’, ā€˜BOM’, ā€˜DEL’) ); Delete existing table (if existing). DROP TABLE IF EXISTS mytable1;
  • 6.
    Data Definition Statements Tablerelated operations Adding columns. ALTER TABLE mytable1 ADD COLUMN firstname varchar(25), ADD COLUMN lastname varchar(40); Deleting columns. ALTER TABLE mytable1 DROP COLUMN firstname, DROP COLUMN lastname; Modifying columns. ALTER TABLE mytable1 MODIFY COLUMN firstname varchar(25), MODIFY COLUMN lastname varchar(40);
  • 7.
    Data Definition Statements Constraints NOTNULL CREATE TABLE mytable1 (col1 INT NOT NULL); PRIMARY KEY CREATE TABLE mytable1 (col1 INT, PRIMARY KEY (col1)); UNIQUE CREATE TABLE mytable1 (col1 INT UNIQUE); FOREIGN KEY CREATE TABLE mytable1 ( col1 INT, FOREIGN KEY(col1) REFERENCES mytable2(mycol) ); DEFAULT CREATE TABLE mytable1 (col1 INT DEFAULT 100);
  • 8.
    Data Manipulation Statements Adding,deleting and updating data (rows) Add a new row (data in all columns). INSERT INTO mytable1 VALUES (ā€˜10’, ā€˜mithun’, ā€˜shanbhag’); Add a new row (data in specific columns). INSERT INTO mytable1 (firstname, lastname) VALUES (ā€˜mithun’, ā€˜shanbhag’); Update row(s). UPDATE mytable1 SET firstname = ā€˜sachin’, lastname = ā€˜tendulkar’ WHERE serialnum = 101; Delete row(s). DELETE FROM mytable1 WHERE firstname = ā€˜mithun’; Delete all row(s). DELETE * FROM mytable1;
  • 9.
    Data Query Statements ā—Data Query Statements ā—‹ Filtering Operations (WHERE) ā—‹ Sorting Operations (ORDER BY) ā—‹ Set Operations (DISTINCT, UNION, UNION ALL) ā—‹ Paging Operations (LIMIT) ā—‹ Aliasing Operations (AS) ā—‹ Aggregation Operations (MIN, MAX, AVERAGE, SUM, COUNT) ā—‹ Grouping Operations (GROUP BY) ā—‹ Join Operations (JOIN)
  • 10.
    Data Query Statements FilteringOperations (WHERE) Extract cities in USA. SELECT * FROM city WHERE countrycode = ’usa’; Extract cities in USA with population greater than 1,000,000. SELECT * FROM city WHERE countrycode = ’usa’ AND population > 1000000; Extract cities in USA or cities with population greater than 1,000,000. SELECT * FROM city WHERE countrycode = ā€˜usa’ OR population > 1000000;
  • 11.
    Data Query Statements FilteringOperations (WHERE) Extract countries starting with ā€˜B’. SELECT * FROM country WHERE name LIKE ’b%’; Extract countries starting with ā€˜B’ and ending with ā€˜a’. SELECT * FROM country WHERE name LIKE ’b%a’; Extract countries which have 5 letters in their name. SELECT * FROM country WHERE name LIKE ’_____’;
  • 12.
    Data Query Statements FilteringOperations (WHERE) Extract countries with no head of state. SELECT * FROM country WHERE headofstate IS NULL; Extract countries which have heads of state. SELECT * FROM country WHERE headofstate IS NOT NULL; Extract countries beginning from letter ā€˜W’ onwards. SELECT * FROM country WHERE name > ’w’; Extract countries with population between 10,000 and 20,000. SELECT * FROM country WHERE population BETWEEN 10000 AND 20000;
  • 13.
    Data Query Statements SortingOperations (ORDER BY) Sort countries by name. SELECT * FROM country ORDER BY name; Sort countries by population (descending). SELECT * FROM country ORDER BY population DESC; Sort countries by continent, then by population (descending). SELECT * FROM country ORDER BY continent, population DESC;
  • 14.
    Data Query Statements SetOperations (DISTINCT) Extract unique continent names SELECT DISTINCT continent FROM country; Extract unique countrycode and district combinations SELECT DISTINCT countrycode, district FROM city;
  • 15.
    Data Query Statements SetOperations (UNION) ā— Combines the result-set of two or more SELECT statements. ā— Each SELECT statement must have the same number of columns, with ā€˜similar’ data types and in the same order. ā— UNION supports only ā€˜distinct’ values, however UNION ALL allows duplicates. Combine the list of country codes from the ā€˜city’ and ā€˜countrylanguage’ tables. SELECT countrycode FROM city UNION SELECT countrycode FROM countrylanguage ORDER BY countrycode;
  • 16.
    Data Query Statements PagingOperations (LIMIT) ā— Constrain the number of rows returned in result set. Extract top 5 countries, sorted by population. SELECT * FROM country ORDER BY population DESC LIMIT 5; Extract countries 6 to 10, sorted by population. SELECT * FROM country ORDER BY population DESC LIMIT 5, 5;
  • 17.
    Data Query Statements AliasingOperations (AS) ā— Gives a table (or column) a temporary, readable name (alias). ā— The alias exists only for the duration of the query. Aliasing a column name. SELECT name AS cityname, population FROM country WHERE cityname = ā€˜new york’; Aliasing a table name. SELECT name, population FROM country as c WHERE c.name = ā€˜new york’;
  • 18.
    Data Query Statements AggregationOperations (MIN, MAX, AVG, SUM, COUNT) Least population. SELECT MIN(population) FROM country; Most population. SELECT MAX(population) FROM country; Average population. SELECT AVG(population) FROM country; Total population. SELECT SUM(population) FROM country; Total number of countries. SELECT COUNT(name) FROM country;
  • 19.
    Data Query Statements GroupingOperations (GROUP BY) ā— Groups the result set using a ā€˜key’. ā— The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM, AVG). Find number of countries in each continent. SELECT continent, count(name) FROM country GROUP BY continent; Group Swedish districts by total population. SELECT district, sum(population) FROM city WHERE countrycode = ā€˜swe’ GROUP BY district;
  • 20.
    Data Query Statements JoinOperations INNER JOIN LEFT OUTER JOIN RIGHT OUTER JOIN FULL OUTER JOIN
  • 21.
    Data Query Statements InnerJoin Display continent information for cities. SELECT id, city.name, countrycode, district, continent FROM city INNER JOIN country ON city.CountryCode = country.code;
  • 22.

Editor's Notes

  • #3Ā System preferences -> mYSql -> enable server PATH=$PATH:/usr/local/mysql/bin
  • #8Ā MySQL does not support CHECK constraints? INDEX has been purposely left out
  • #9Ā SQL UPDATE - Don’t forget the WHERE clause, else all rows will be updated.
  • #11Ā String comparison is case insensitive Comparison operators on string, numbers, date Collation, character sets
  • #12Ā String comparison is case insensitive Comparison operators on string, numbers, date Collation, character sets
  • #13Ā String comparison is case insensitive Comparison operators on string, numbers, date Collation, character sets
  • #16Ā Need a better example.
  • #17Ā Question: How will you do countries 11 - 20 in this list?
  • #18Ā Database.table.column. We’ve not covered dot notations yet.
  • #20Ā GROUP BY DESC