You are on page 1of 25

SQL is a standard language for accessing and manipulating databases.

What is SQL?
SQL stands for Structured Query Language
SQL lets you access and manipulate databases
SQL became a standard of the American National Standards Institute (ANSI) in 1986, and of the
International Organization for Standardization (ISO) in 1987

What Can SQL do?


 SQL can execute queries against a database
 SQL can retrieve data from a database
 SQL can insert records in a database
 SQL can update records in a database
 SQL can delete records from a database
 SQL can create new databases
 SQL can create new tables in a database
 SQL can create stored procedures in a database
 SQL can create views in a database
 SQL can set permissions on tables, procedures, and views

Although SQL is an ANSI/ISO standard, there are different versions of the SQL language.
However, to be compliant with the ANSI standard, they all support at least the major commands (such
as SELECT, UPDATE, DELETE, INSERT, WHERE) in a similar manner.

SQL manipulate databases


 It is specifically designed for data manipulation
 It has proven reliability and has been around for long time which is 50 years
 It has a large community of users
 It is simple to learn the basics
 It has a powerful instruction set for more advanced users like data manipulation

Using SQL in Your Web Site


To build a web site that shows data from a database, you will need:
 An RDBMS database program (i.e. MS Access, SQL Server, MySQL)
 To use a server-side scripting language, like PHP or ASP
 To use SQL to get the data you want
 To use HTML / CSS to style the page
RDBMS
RDBMS stands for Relational Database Management System.
RDBMS is the basis for SQL, and for all modern database systems such as MS SQL Server, IBM DB2,
Oracle, MySQL, and Microsoft Access.
The data in RDBMS is stored in database objects called tables. A table is a collection of related data
entries and it consists of columns and rows.

The owner of the online store uses structured query language (SQL) to get information from the
database.
Give three reasons why SQL is used to manipulate data in databases.

Some of The Most Important SQL Commands


SELECT - extracts data from a database
UPDATE - updates data in a database
DELETE - deletes data from a database
INSERT INTO - inserts new data into a database
CREATE DATABASE - creates a new database
ALTER DATABASE - modifies a database
CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
CREATE INDEX - creates an index (search key)
DROP INDEX - deletes an index

CUSTOMER Table
SELECT Statement
SELECT Column Example
SELECT CustomerName, City FROM Customers;

SELECT * Example
SELECT * FROM Customers;
SELECT Country FROM Customers;

SELECT DISTINCT Statement


SELECT COUNT(DISTINCT Country) FROM Customers;
SELECT Count(*) AS DistinctCountries FROM (SELECT DISTINCT Country FROM Customers);

WHERE Syntax
SELECT * FROM Customers WHERE Country='Mexico';
SELECT * FROM Customers WHERE CustomerID=1;

AND, OR and NOT Operators


AND Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;

SELECT * FROM Customers WHERE Country='Germany' AND City='Berlin';

OR Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;

SELECT * FROM Customers WHERE City='Berlin' OR City='München';

NOT Syntax
SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;

SELECT * FROM Customers WHERE NOT Country='Germany';


Combining AND, OR and NOT
SELECT * FROM Customers WHERE Country='Germany' AND (City='Berlin' OR City='München');
SELECT * FROM Customers WHERE NOT Country='Germany' AND NOT Country='USA';

Display all fields where city is “Maxico D.F”.


Display all fields from customer table and where city is “Berlin” or “London”.
Write a SQL statements and returns the results form the Customer table, where the country is not
“Maxico”.
Write a SQL statements and returns the results form the Customer table, where the country is not
“Maxico” and country is not “UK”.

Exercises: (Survey Table)


1. Write a query that returns the year, month, day, species ID and weight (in mg).
SELECT *
FROM
2. Write a query that returns the day, month, year, species ID, and weight (in kg) for individuals caught
on Plot 1 that weigh more than 75 g.
3. Write a query that returns day, month, year, species ID for individuals caught in January, May and
July.
4. Display the first name and department number for all customers whose last name is “De Haan”
(Employees table).
SELECT first name, department number
FROM Employees table
WHERE last name = “De Haan”;
5. Display all data from Departments table for Sales department (department_name column).
SELECT *
FROM Departments
WHERE departmentname=”Sales department”;
6. Display the first name, last_name, department number and salary for all employees who earn more
than 9700 (Employees table).
SELECT firstname, lastname, departmentnumber, salary
FROM Employees table
WHERE Salary > 9700;
7. Display the first name, last name, package number and monthly discount for all customers with
monthly discount less than 30 (Customers table).
SELECT firstname, lastname, packagenumber, monthly discount
FROM Customers
WHERE monthly discount< 30;
ORDER BY Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;

SELECT * FROM Customers ORDER BY Country;

ORDER BY DESC
SELECT * FROM Customers ORDER BY Country DESC;

ORDER BY Several Columns


SELECT * FROM Customers ORDER BY Country, CustomerName;
SELECT * FROM Customers ORDER BY Country ASC, CustomerName DESC;

INSERT INTO Statement


INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);

INSERT INTO table_name


VALUES (value1, value2, value3, ...);

INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)


VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');

Insert Data Only in Specified Columns


INSERT INTO Customers (CustomerName, City, Country) VALUES ('Cardinal', 'Stavanger', 'Norway');

ROUND() Function
ROUND(number, decimals)

SELECT ROUND(235.415, 2)

SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;

SELECT SUM(Quantity) FROM OrderDetails; OR


SELECT SUM(Quantity) AS TotalItemsOrdered FROM OrderDetails;
MIN() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
SELECT MIN(Price) AS SmallestPrice FROM Products;

MAX() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;

SELECT MAX(Price) AS LargestPrice FROM Products;

COUNT() and AVG() Function


COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;

SELECT COUNT(ProductID) FROM Products;


DISTINCT column_name
SELECT DISTINCT sex FROM Employee
ANS: Female, Male, Others

COUNT (DISTINCT column_name)


SELECT COUNT(DISTINCT sex) FROM Employee
ANS : 3

AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;

SELECT AVG(Price) FROM Products;

GROUP BY Statement
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);

SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country;


SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;

Exercises: (Survey Table)


8. Display the lowest last name alphabetically (Employees table).
SELECT MIN(lastname) AS MinLastName
FROM Employees ;
9. Display the highest last name alphabetically (Employees table).
SELECT MAX(lastname) AS MaxLastName
FROM Employees;
10. Display the number of rows in Employees table.
SELECT COUNT(EmployeeID) AS NumberRow
FROM Employees;
11. Write a query that returns year, species ID, and weight in kg from the surveys table, sorted with
the largest weights at the top.
SELECT Year, speciesID, weight
12. Write a query that returns the number of each species caught in each year sorted from most often
caught species to the least occurring ones within each year starting from the most recent records.
13. Using the surveys table write a query to display the three date fields, species ID, and weight in
kilograms (rounded to two decimal places), for rodents captured in 1999, ordered alphabetically by the
species ID.
14. Write query that returns: total weight, average weight, and the min and max weights for all animals
caught over the duration of the survey. Can you modify it so that it outputs that for a range of weights?

15. Write queries that return:


How many individuals were counted in each year.
Average weight of each species in each year.

NULL Values
A field with a NULL value is a field with no value

IS NULL Syntax
SELECT column_names
FROM table_name
WHERE column_name IS NULL;
SELECT CustomerName, ContactName, Address FROM Customers WHERE Address IS NULL;

IS NOT NULL Syntax


SELECT column_names
FROM table_name
WHERE column_name IS NOT NULL;

SELECT CustomerName, ContactName, Address FROM Customers WHERE Address IS NOT NULL;

SQL UPDATE Statement


UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

UPDATE Customers SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'


WHERE CustomerID = 1;

UPDATE Multiple Records


UPDATE Customers SET ContactName='Juan' WHERE Country='Mexico';
UPDATE Customers SET ContactName='Juan';

Note : Be careful when updating records. If you omit the WHERE clause, ALL records will be updated!

DELETE Statement
DELETE FROM table_name WHERE condition;
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

Delete All Records


DELETE FROM table_name;
DELETE FROM Customers;

16. In products table, update the product_name to 'Grapefruit' for all records whose product_name is
"Apple".
17. In suppliers table populated with the following data, update the city to 'Boise' and the state to
"Idaho" for all records whose supplier_name is "Microsoft".
18. The first_name field is set to 'Judy' in the customers table where the customer_id is equal to 8000.
19. In the supplier table, update the supplier_id to 150, the supplier_name to 'Apple' and city to
'Cupertino' where the supplier_name is 'Google'.
SELECT TOP
SELECT TOP number|percent column_name(s)
FROM table_name
WHERE condition;

SELECT TOP 3 * FROM Customers;

LIMIT
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;

SELECT * FROM Customers LIMIT 3;

ROWNUM
SELECT column_name(s)
FROM table_name
WHERE ROWNUM <= number;

SELECT * FROM Customers WHERE ROWNUM <= 3;

SQL TOP PERCENT


SELECT TOP 50 PERCENT * FROM Customers; (50%)

ADD a WHERE
SELECT TOP 3 * FROM Customers WHERE Country='Germany';
SELECT * FROM Customers WHERE Country='Germany' LIMIT 3;
SELECT * FROM Customers WHERE Country='Germany' AND ROWNUM <= 3;

LIKE Operator
There are two wildcards often used in conjunction with the LIKE operator:
(1) % - The percent sign represents zero, one, or multiple characters
(2) _ - The underscore represents a single character
SELECT column1, column2, ...
FROM table_name
WHERE columnN LIKE pattern;

SELECT * FROM Customers WHERE CustomerName LIKE 'a%'; [CustomerName ending with "a":]
SELECT * FROM Customers WHERE CustomerName LIKE '%a'; [CustomerName that have "or" in any
position]
SELECT * FROM Customers WHERE CustomerName LIKE '%or%'; [CustomerName that have "or" in
any position]
SELECT * FROM Customers WHERE CustomerName LIKE '_r%'; [CustomerName that have "r" in the
second position]
SELECT * FROM Customers WHERE CustomerName LIKE 'a__%'; [CustomerName that starts with
"a" and are at least 3 characters in length]
SELECT * FROM Customers WHERE ContactName LIKE 'a%o'; [ContactName that starts with "a"
and ends with "o]

NOT LIKE
SELECT * FROM Customers WHERE CustomerName NOT LIKE 'a%'; [CustomerName that does NOT
start with "a"]

Wildcard Characters
Using the % Wildcard
SELECT * FROM Customers WHERE City LIKE 'ber%'; [City starting with "ber"]
SELECT * FROM Customers WHERE City LIKE '%es%'; [City containing the pattern "es"]

Using the _ Wildcard


SELECT * FROM Customers WHERE City LIKE '_ondon'; [City starting with any character, followed
by "ondon]
SELECT * FROM Customers WHERE City LIKE 'L_n_on'; [City starting with "L", followed by any
character, followed by "n", followed by any character, followed by "on"]

[charlist] Wildcard
SELECT * FROM Customers WHERE City LIKE '[bsp]%'; [City starting with "b", "s", or "p]
SELECT * FROM Customers WHERE City LIKE '[a-c]%'; [City starting with "a", "b", or "c"]

[!charlist] Wildcard
SELECT * FROM Customers WHERE City LIKE '[!bsp]%'; [City NOT starting with "b", "s", or "p"]
SELECT * FROM Customers WHERE City NOT LIKE '[bsp]%';

IN Operator
SELECT column_name(s)
FROM table_name
WHERE column_name IN (value1, value2, ...);

SELECT column_name(s)
FROM table_name
WHERE column_name IN (SELECT STATEMENT);

SELECT * FROM Customers WHERE Country IN ('Germany', 'France', 'UK'); [customers that are
located in "Germany", "France" or "UK"]
SELECT * FROM Customers WHERE Country NOT IN ('Germany', 'France', 'UK'); [customers that are
NOT located in "Germany", "France" or "UK"]

SELECT * FROM Customers WHERE Country IN (SELECT Country FROM Suppliers); [all customers
that are from the same countries as the suppliers]

20. Display all records who’s name starts with A and ends with n
SELECT * FROM CUSTOMER WHERE CustomerName LIKE “A%n”;
21. Display all records who’s name have no ( case sensitive )
SELECT * FROM customer WHERE name LIKE binary ‘%no%’;
22. Display all records who got mark in nineties but not equal to 100
23. Display all records who have alex or deo any where in name column
24. Display all records who have alex and Jon any where in name column
25. Display all records who have ro any where in name column and got mark in nineties
26. Retrieve the prod_id and prod_name fields from a table named Products if the prod_name contains
the string 'bean bag'
27. Select the columns prod_id and prod_name from the Products table. Return the rows whose
prod_name begins with the string 'Fish' and is followed by 0 or more occurrences of any character.
28. Select the column prod_name from the Products table. Return the rows whose prod_name begins
with any number of occurences of any character, followed by 'bean b', followed by a single instance
of any character, followed by 'g', followed by any number of occurrences of any character.

SQL BETWEEN Operator


SELECT column_name(s)
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
BETWEEN
SELECT * FROM Products WHERE Price BETWEEN 10 AND 20; [price BETWEEN 10 and 20]

NOT BETWEEN
SELECT * FROM Products WHERE Price NOT BETWEEN 10 AND 20;

BETWEEN with IN
SELECT * FROM Products WHERE Price BETWEEN 10 AND 20 AND CategoryID NOT IN (1,2,3);

BETWEEN Text Values


SELECT * FROM Products WHERE ProductName BETWEEN 'Carnarvon Tigers' AND 'Mozzarella di
Giovanni' ORDER BY ProductName; [ProductName BETWEEN Carnarvon Tigers and Mozzarella di
Giovanni]
SELECT * FROM Products WHERE ProductName BETWEEN "Carnarvon Tigers" AND "Chef Anton's
Cajun Seasoning" ORDER BY ProductName; [ProductName BETWEEN Carnarvon Tigers and Chef
Anton's Cajun Seasoning]

NOT BETWEEN Text Values


SELECT * FROM Products WHERE ProductName NOT BETWEEN 'Carnarvon Tigers' AND 'Mozzarella
di Giovanni' ORDER BY ProductName; [ProductName NOT BETWEEN Carnarvon Tigers and
Mozzarella di Giovanni]

BETWEEN Dates
SELECT * FROM Orders WHERE OrderDate BETWEEN #01/07/1996# AND #31/07/1996#;
SELECT * FROM Orders WHERE OrderDate BETWEEN '1996-07-01' AND '1996-07-31';

Alias Column Syntax (to give a table, or a column in a table, a temporary name)
SELECT column_name AS alias_name
FROM table_name;
SELECT CustomerID AS ID, CustomerName AS Customer FROM Customers;

Alias Table Syntax


SELECT column_name(s)
FROM table_name AS alias_name;
SELECT CustomerName AS Customer, ContactName AS [Contact Person] FROM Customers;
SELECT CustomerName, Address + ', ' + PostalCode + ' ' + City + ', ' + Country AS Address
FROM Customers;

SELECT CustomerName, CONCAT(Address,', ',PostalCode,', ',City,', ',Country) AS Address


FROM Customers;

CustomerName Address

Alfreds Futterkiste  Obere Str. 57, 12209 Berlin, Germany 

Ana Trujillo Emparedados Avda. de la Constitución 2222, 05021 México D.F.,


y helados  Mexico 
Alias for Tables
SELECT o.OrderID, o.OrderDate, c.CustomerName
FROM Customers AS c, Orders AS o
WHERE c.CustomerName='Around the Horn' AND c.CustomerID=o.CustomerID;

SELECT Orders.OrderID, Orders.OrderDate, Customers.CustomerName


FROM Customers, Orders
WHERE Customers.CustomerName='Around the Horn' AND
Customers.CustomerID=Orders.CustomerID;

OrderID OrderDate CustomerName

10355 1996-11-15 Around the Horn

10383 1996-12-16 Around the Horn

SQL JOIN
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate FROM Orders INNER JOIN
Customers ON Orders.CustomerID=Customers.CustomerID;

INNER JOIN

SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
SELECT Orders.OrderID, Customers.CustomerName FROM Orders INNER JOIN Customers ON
Orders.CustomerID = Customers.CustomerID;

JOIN Three Tables


SELECT Orders.OrderID, Customers.CustomerName, Shippers.ShipperName
FROM ((Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);

LEFT JOIN
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;

SELECT Customers.CustomerName, Orders.OrderID FROM Customers


LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;

RIGHT JOIN
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID ORDER BY
Orders.OrderID;

FULL OUTER JOIN


SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;

SELECT Customers.CustomerName, Orders.OrderID FROM Customers FULL OUTER JOIN Orders ON


Customers.CustomerID=Orders.CustomerID ORDER BY Customers.CustomerName;

Self JOIN
SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;

SELECT A.CustomerName AS CustomerName1, B.CustomerName AS CustomerName2, A.City


FROM Customers A, Customers B WHERE A.CustomerID <> B.CustomerID
AND A.City = B.City ORDER BY A.City;

Employees (Employee_Id, First_name, Last_name, Email, Phone_number, Hire_date, Job_Id, Salary,


commission_pct , manager_id , department_id)
Departments (department_id , department_name , manager_id , location_id)
Locations (location_id ,street_address, postal_code , city , state_province , country_id)
Countries (country_id, country_name, region_id)
job_history (employee_id ,start_date , end_date, job_id, department_id)
jobs (job_id , job_title , min_salary, max_salary)
job_grade (grade_level , lowest_sal, highest_sal)

30. Write a query in SQL to display the first name, last name, department number, and department
name for each employee.
31. Write a query in SQL to display the first and last name, department, city, and state province for each
employee.
32. Write a query in SQL to display the first name, last name, department number and department
name, for all employees for departments 80 or 40 order by Last_name.
SELECT e.first_name, e.Last_name, d.department_id, d.department_name
33. Write a query in SQL to display those employees who contain a letter z to their first name and also
display their last name, department, city, and state province.
SELECT e,First_name, e.Last_name, d.department_id, l.city, l.State_province
FROM Employees AS e
INNER JOIN Department AS d
ON e.department_id=d.department_id
INNER JOIN Location AS l
ON d.location_id = l.location_id
WHERE e.Last_name LIKE “%z%”;
34. Write a query in SQL to display all departments including those where does not have any employee.
SELECT e.fist_name,
e.last_name,
d.department_name
FROM department d
LEFT JOIN employees e
ON e.department_id = d.department_id
35. Write a query in SQL to display the department name, city, and state province for each department.
36. Write a query in SQL to display the first name, last name, department number and name, for all
employees who have or have not any department.
37. Write a query in SQL to display the first name of all employees and the first name of their manager
including those who does not working under any manager.
SELECT e1.first_name AS "employee_name",
e2.first_name AS "manager_name"
FROM employees e1
LEFT JOIN employees e2
ON e1.manager_id = e2.employee_id;
38. Write a query in SQL to display the first name, last name, and department number for those
employees who works in the same department as the employee who holds the last name as Taylor.
SELECT e1.first_name,
e1.last_name,
e1.department_id
FROM employees e1
INNER JOIN employees e2
ON e1.department_id = e2.department_id
AND e2.last_name = 'Taylor';
39. Write a query in SQL to display the job title, department name, full name (first and last name ) of
employee, and starting date for all the jobs which started on or after 1st January, 1993 and ending
with on or before 31 August, 1997
SELECT j.job_title,
d.department_name,
CONCAT(e.first_name, ' ', e.last_name) AS full_name,
jh.start_date
FROM employees e
INNER JOIN job_history jh
ON e.employee_id = jh.employee_id
AND jh.start_date BETWEEN '1993-01-01' AND '1997-08-31'
INNER JOIN jobs j
ON jh.job_id = j.job_id
INNER JOIN departments d
ON jh.department_id = d.department_id;
40. Write a query in SQL to display job title, full name (first and last name ) of employee, and the
difference between maximum salary for the job and salary of the employee.
SELECT j.job_title,
CONCAT(e.first_name, ' ', e.last_name) AS full_name,
(j.max_salary - e.salary) AS salary_diff
FROM employees e
INNER JOIN jobs j
ON e.job_id = j.job_id;
41. Write a query in SQL to display the name of the each department, average salary and number of
employees working in that department who got commission.
SELECT d.department_name,
AVG (e.salary),
COUNT (e. commission_pct)
FROM employees e
INNER JOIN department d
ON e.depatment_id = d.department_id
GROUP BY (d,department_name)
42. Write a query in SQL to display the full name (first and last name) of employees, job title and the
salary differences to their own job for those employees who is working in the department ID 80.
43. Write a query in SQL to display the name of the country, city, and the departments which are
running there that means same country and same location.
SELECT d.department_name,
l.city,
c.county
FROM department d
INNER JOIN location l
ON d.location_id = l.location_id
INNER JOIN countries c
ON l.country_id = c.country_id
44. Write a query in SQL to display job title and average salary of employees.
45. Employees and departments (Employees & Departments tables)
For each employee, display the first name, last name, department number and department name.
Display the first name, last name, department number and department name, for all employees in
departments 50 or 90.
46. Departments and locations (Departments, Employees & Locations tables)
For each department, display the department name, city, and state province.
For each employee, display the full name, department name, city, and state province.
Display the full name, department name, city, and state province, for all employees whose last name
contains the letter a.

UNION Operator
The UNION operator is used to combine the result-set of two or more SELECT statements.
 Each SELECT statement within UNION must have the same number of columns
 The columns must also have similar data types
 The columns in each SELECT statement must also be in the same order
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;

SELECT City FROM Customers UNION SELECT City FROM Suppliers ORDER BY City;

UNION ALL Syntax


SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;

SELECT City FROM Customers UNION ALL SELECT City FROM Suppliers ORDER BY City;

UNION With WHERE [only distinct values]


SELECT City, Country FROM Customers WHERE Country='Germany' UNION SELECT City, Country
FROM Suppliers WHERE Country='Germany' ORDER BY City;
UNION ALL With WHERE [duplicate values also]
SELECT City, Country FROM Customers WHERE Country='Germany' UNION ALL SELECT City,
Country FROM Suppliers WHERE Country='Germany' ORDER BY City;

SELECT 'Customer' AS Type, ContactName, City, Country FROM Customers UNION


SELECT 'Supplier', ContactName, City, Country FROM Suppliers;

GROUP BY With JOIN


SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID GROUP BY ShipperName;

HAVING
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);

SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country


HAVING COUNT(CustomerID) > 5;
SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country
HAVING COUNT(CustomerID) > 5 ORDER BY COUNT(CustomerID) DESC;

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;

EXISTS Operator
SELECT column_name(s)
FROM table_name
WHERE EXISTS
(SELECT column_name FROM table_name WHERE condition);
SELECT SupplierName FROM Suppliers
WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID =
Suppliers.supplierID AND Price < 20);

SELECT SupplierName FROM Suppliers


WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID =
Suppliers.supplierID AND Price = 22);

ANY and ALL Operators


SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name FROM table_name WHERE condition);

SELECT ProductName
FROM Products
WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails WHERE Quantity = 10);

SELECT ProductName
FROM Products
WHERE ProductID = ANY (SELECT ProductID FROM OrderDetails WHERE Quantity > 99);

SELECT INTO Statement


Copy all columns into a new table:
SELECT *
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;

Copy only some columns into a new table:


SELECT column1, column2, column3, ...
INTO newtable [IN externaldb]
FROM oldtable
WHERE condition;

SELECT * INTO CustomersBackup2017 FROM Customers; [backup copy]


SELECT * INTO CustomersBackup2017 IN 'Backup.mdb' FROM Customers; [new table in another
database]
SELECT CustomerName, ContactName INTO CustomersBackup2017 FROM Customers; [copies only
a few columns into a new table]

SELECT * INTO CustomersGermany FROM Customers WHERE Country = 'Germany'; [copies only
the German customers into a new table]

SELECT Customers.CustomerName, Orders.OrderID INTO CustomersOrderBackup2017


FROM Customers LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID; [copies data
from more than one table into a new table]

SELECT INTO can also be used to create a new, empty table using the schema of another. Just add a
WHERE clause that causes the query to return no data
SELECT * INTO newtable
FROM oldtable
WHERE 1 = 0;

INSERT INTO SELECT Statement


 The INSERT INTO SELECT statement copies data from one table and inserts it into another table.
 INSERT INTO SELECT requires that data types in source and target tables match
 The existing records in the target table are unaffected

Copy all columns from one table to another table:


INSERT INTO table2
SELECT * FROM table1
WHERE condition;
Copy only some columns from one table into another table:
INSERT INTO table2 (column1, column2, column3, ...)
SELECT column1, column2, column3, ...
FROM table1
WHERE condition;

Copies "Suppliers" into "Customers" (the columns that are not filled with data, will contain NULL)
INSERT INTO Customers (CustomerName, City, Country) SELECT SupplierName, City, Country
FROM Suppliers;

Copies "Suppliers" into "Customers" (fill all columns) INSERT INTO Customers (CustomerName,
ContactName, Address, City, PostalCode, Country) SELECT SupplierName, ContactName, Address,
City, PostalCode, Country FROM Suppliers;

Copies only the German suppliers into "Customers" INSERT INTO Customers (CustomerName, City,
Country) SELECT SupplierName, City, Country FROM Suppliers WHERE Country='Germany';

SQL CASE Statement


CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN conditionN THEN resultN
ELSE result
END;

SELECT OrderID, Quantity,


CASE
WHEN Quantity > 30 THEN 'The quantity is greater than 30'
WHEN Quantity = 30 THEN 'The quantity is 30'
ELSE 'The quantity is under 30'
END AS QuantityText
FROM OrderDetails;

SELECT CustomerName, City, Country


FROM Customers
ORDER BY
(CASE
WHEN City IS NULL THEN Country
ELSE City
END);
NULL Functions
SELECT ProductName, UnitPrice * (UnitsInStock + UnitsOnOrder) FROM Products;
SELECT ProductName, UnitPrice * (UnitsInStock + IFNULL(UnitsOnOrder, 0)) FROM Products;
SELECT ProductName, UnitPrice * (UnitsInStock + ISNULL(UnitsOnOrder, 0)) FROM Products;

CREATE DATABASE Statement


CREATE DATABASE databasename;

CREATE DATABASE testDB;


BACKUP DATABASE for SQL Server
BACKUP DATABASE databasename TO DISK = 'filepath';

BACKUP DATABASE testDB TO DISK = 'D:\backups\testDB.bak';

CREATE TABLE Statement


CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

PRIMARY KEY Constraint


CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);

OR
CREATE TABLE Persons (
ID int NOT NULL PRIMARY KEY,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int
);

FOREIGN KEY Constraint


CREATE TABLE Orders (
OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
OR
CREATE TABLE Orders (
OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int FOREIGN KEY REFERENCES Persons(PersonID)
);

AUTO INCREMENT Field


CREATE TABLE Persons (
Personid int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (Personid)
);

You might also like