Вы находитесь на странице: 1из 8

UCAI

Introduction to SQL
Exercise 0: Introduction
Lets say youre working as an analyst at an insurance company. Your manager hands you a stake
of handwritten claims applications, and tells you to create a searchable database. You say, aha,
Ill make a Excel table! Your manager frowns, and says, Excels too bulky. Use SQL instead. As
someone who doesnt know what SQL is, you begin to sweat Lucky for you, were here to get
you up to speed on all you need to know to carry out this task, and more!
Go to http://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all
What is SQL? Structured Query Language is a special-purpose programming language designed
for managing data held in a relational database management system (RDBMS). Why is it
important? Its high-level, semantically initiative, and compatible with any data-oriented
program.
Exercise 1: Creating Tables
So we have a pack of applications. The first thing we want to do is create a table to house these
applications.
CREATE TABLE claim (
id INTEGER PRIMARY KEY,
first_name VARCHAR,
last_name VARCHAR,
amount_paid REAL,
sub_time TIMESTAMP
);
Exercise 2: Linking Tables
One table is boring. Your manager drops by, and hands you another stack, this time, with the
characteristics of peoples cars.
So you create another Table:
CREATE TABLE car (
id INTEGER PRIMARY KEY,
make TEXT,
model TEXT,
when_insured DATE
);
Great. But how do we know which car has which claim?
Create another table!
CREATE TABLE claim_car (

claim_id INTEGER,
car_id INTEGER
);
The question is, why not just do something like
CREATE TABLE car (
id INTEGER PRIMARY KEY,
make TEXT,
model TEXT,
when_insured DATE
claim_id INTEGER
);
The answer to that lies in the theory of normal forms, which we wont get into. But the theory
behind creating efficient databases tells us to do it as such. Its a fascinating field, and it would
definitely be worth your while to read up on it.
Examples 3: Inserting Data
Ok, we got two piles of paper. Lets start inputting them.
INSERT INTO claim (id, first_name, last_name, amount_paid, sub_time)
VALUES (0, "Zed", "Shaw", 1200, 20151212
);
INSERT INTO car (id, make, model, when_insured)
VALUES (0, "Audi", "X1", 20141223);
INSERT INTO car VALUES (1, "Honda", "Civic", 20121201);
The second version is an abbreviated version that doesn't specify the columns and instead relies
on the implicit order in the table. This form is dangerous since you don't know what column your
statement is actually accessing, and some databases don't have reliable ordering for the columns.
It's best to only use this form when you're really lazy.

The only thing that's missing is which car gets which claim, and that data goes into the table like
this:

INSERT INTO claim_car (claim_id, car_id) VALUES (0, 0);


INSERT INTO claim_car VALUES (0, 1);
Exercise 4: Selecting Data

SELECT * FROM claim;


SELECT make, model FROM car;
SELECT make, model FROM car WHERE when_insured > 20140301;
SELECT * FROM claim WHERE first_name != "Zed";

Exercise 5: Joining Tables


Great, you managed to get all the data in. Now lets do some combining: Well first look at
Products, Suppliers and Categories.
Products
ProductID

ProductName

SupplierID

Suppliers
SupplierID SupplierName Contact Name Address
Phone
Categories
CategoryID
CategoryName
Description

CategoryID

City

Unit

PostalCode

Price

Country

We want to know which suppliers give us which products, and which products belong to which
category. All in one table.
SELECT Products.ProductID, Products.ProductName, Categories.CategoryName,
Suppliers.SupplierName
FROM Products, Categories, Suppliers
WHERE
Products.CategoryID = Categories.CategoryID AND
Products.SupplierID = Suppliers.SupplierID ;
Exercise 6: Deleting Data
Lets say a certain supplier no longer works with us. How do we delete him and his products
from the system?
DELETE FROM suppliers WHERE supplierID = 1;
delete from products where supplierID = 1;
As you can see, if you want to remove all traces of a supplier, you have to manually delete its
products. Is there a way to automate this process? Yes. We wont cover it here.
If you want to delete an entire table,
Drop table car;

This is permanent.
Exercise 7: Updating Data
What if one of your suppliers changed their name? Is there a way for us to update the table? Yes.
UPDATE suppliers SET SupplierName = "Harolds"
WHERE SupplierName = "New Orleans Cajun Delights";
UPDATE products SET supplierID = 2
WHERE Productid=6;
SELECT * FROM suppliers;
SELECT * FROM products;
Intermezzo: SQL Injection
Phew, that was a lot of information.

Exercise 8: Where oh where


We covered SQL on the surface. Now lets dig into the Select function. Well first focus on the
Where clause.
You already seen the equal sign being used, but there are other operators that are useful as well!
They are: <>, >, <, >=, <=, between (an inclusive range), like, and in.
Most of these should be somewhat intuitive. Lets explore the last 3.
SELECT * FROM products where SupplierID between 2 and 4;
SELECT * FROM products where SupplierID NOT between 2 and 4;
SELECT * FROM products where ProductName between A and C;
Select * From Products where ProductName like "%s";
%
_
[charlist]
[!charlist]

A substitute for zero or more characters


A substitute for a single character
Sets and ranges of characters to match
Matches only a character NOT specified within the brackets

What we just touched upon is a whole field of computer science called regular expressions.
Select * From Products where ProductName in ("Queso Cabrales", "Sir Rodney's Scones");
AND/OR
And/or are used to filter results based on more than one condition.
Select * From Products where SupplierID = 3 and CategoryID = 2;
Select * From products where SupplierID = 3 and (CategoryID=2 or CategoryID=4);
Exercise 9: ordering tables
The ORDER BY keyword is used to sort the result-set by one or more columns.
The ORDER BY keyword sorts the records in ascending order by default. To sort the records in a
descending order, you can use the DESC keyword.
SELECT * FROM Customers ORDER BY Country DESC;
SELECT * FROM Customers ORDER BY Country, CustomerName;
Select * From Products where SupplierID = 3 order by Price;
Select * From Products order by Price where SupplierID = 3;
Exercise 10: Aliases
SQL aliases are used to give a database table, or a column in a table, a temporary name.
Basically aliases are created to make column names more readable.
SELECT CustomerName AS Customer, ContactName AS [Contact Person] FROM Customers;
SELECT CustomerName, Address+', '+City+', '+PostalCode+', '+Country AS Address FROM
Customers;
Note: to get the above on mySQL, use
SELECT CustomerName, CONCAT(Address,', ',City,', ',PostalCode,', ',Country) AS Address
FROM Customers;
Exercise 11: Joining in Depth
Inner Join
Left Join
Right Join
Full Join
Union
Exercise 12: Create Constraints
NOT NULL - Indicates that a column cannot store NULL value
UNIQUE - Ensures that each row for a column must have a unique value

PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Ensures that a column (or
combination of two or more columns) have a unique identity which helps to find a particular
record in a table more easily and quickly
FOREIGN KEY - Ensure the referential integrity of the data in one table to match values in
another table
CHECK - Ensures that the value in a column meets a specific condition
DEFAULT - Specifies a default value for a column
Exercise 13: Data Entry in Depth
Null
Dates
Alter
Create Index
Auto Increment
Exercise 14: Functions
Aggregate Functions
AVG() - Returns the average value
COUNT() - Returns the number of rows
FIRST() - Returns the first value
LAST() - Returns the last value
MAX() - Returns the largest value
MIN() - Returns the smallest value
SUM() - Returns the sum
SELECT AVG(Price) AS PriceAverage FROM Products;
SELECT ProductName, Price FROM Products WHERE Price>(SELECT AVG(Price) FROM
Products);
SELECT COUNT(CustomerID) AS OrdersFromCustomerID7 FROM Orders WHERE
CustomerID=7;
SELECT COUNT(*) AS NumberOfOrders FROM Orders;
SELECT COUNT(DISTINCT CustomerID) AS NumberOfCustomers FROM Orders;
SELECT MAX(Price) AS HighestPrice FROM Products;
SELECT SUM(Quantity) AS TotalItemsOrdered FROM OrderDetails;
Scalar Functions
UCASE() - Converts a field to upper case
LCASE() - Converts a field to lower case
MID() - Extract characters from a text field
LEN() - Returns the length of a text field
ROUND() - Rounds a numeric field to the number of decimals specified
SELECT UCASE(CustomerName) AS Customer, City FROM Customers;
SELECT MID(City,1,4) AS ShortCity FROM Customers;

SELECT CustomerName,LEN(Address) as LengthOfAddress FROM Customers;


SELECT ProductName, ROUND(Price,0) AS RoundedPrice FROM Products;
Others
Group By - used in conjunction with the aggregate functions to group the result-set by one or
more columns.
Having Used for aggregate functions in place of WHERE
SELECT Shippers.ShipperName,COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID=Shippers.ShipperID
GROUP BY ShipperName;
SELECT Shippers.ShipperName, Employees.LastName,
COUNT(Orders.OrderID) AS NumberOfOrders
FROM ((Orders INNER JOIN Shippers ON Orders.ShipperID=Shippers.ShipperID)
INNER JOIN Employees ON Orders.EmployeeID=Employees.EmployeeID)
GROUP BY ShipperName,LastName;
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM (Orders
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID)
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 10;
SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID
WHERE LastName='Davolio' OR LastName='Fuller'
GROUP BY LastName
HAVING COUNT(Orders.OrderID) > 25;

Credit goes to:


http://sql.learncodethehardway.org/book/
http://www.w3schools.com/sql/

Вам также может понравиться