SlideShare ist ein Scribd-Unternehmen logo
1 von 35
Downloaden Sie, um offline zu lesen
SQL
Easy to Learn
Anupam
SQL Tutorial: Introduction
What is SQL?
 SQL is a language used to retrieve and manipulate data in a RDMS.
 SQL stands for Structured Query Language.
What is a Database?
 A database is a place to store data.
 A relational database system (RDMS) stores data in tables.
Relational Database Tables
A relational database stores data in tables. Each table has a number of rows and
columns.
The table below has 4 rows and 3 columns.
SQL and Relational Databases
A relational database contains tables which store data that is related in some way.
SQL is the language that allows retrieval and manipulation of table data in a
relational database.
The database below has 2 tables: one with data on Users and another with data
on Products.
.
Example database
This tutorial uses a database which is a modernized version of Microsoft's
Northwind database. Northwind is a fictitious store that sells specialty food
products from all over the world. The database has 5 tables.
Below are an Entity Relationship Diagram (ERD) which shows the tables and their
relationships.
SQL Syntax
 The syntax of a language describes the language elements.
 SQL statements are somewhat like simple English sentences.
 Keywords include SELECT, UPDATE, WHERE, ORDER BY, etc.
 ANSI Standard SQL is the lingua franca for relational databases.
The SQL Syntax
SQL was designed to be entered on a console and results would display back to a
screen.
Today, SQL is mostly used by programmers who use SQL inside their language to
build applications that access data in a database.
Four fundamental operations that apply to any database are:
1. Read the data -- SELECT
2. Insert new data -- INSERT
3. Update existing data -- UPDATE
4. Remove data -- DELETE
Collectively these are referred to as CRUD (Create, Read, Update, and Delete).
The general form for each of these 4 operations in SQL is presented next.
The SQL SELECT general form
1. SELECT column-names FROM table-name WHERE condition
ORDER BY sort-order
Example:
1. SELECT FirstName, LastName, City, Country FROM Customer
WHERE City = 'Paris' ORDER BY LastName
The SQL INSERT general form
1. INSERT table-name (column-names) VALUES (column-values)
Example:
1. INSERT Supplier (Name, ContactName, City, Country)
VALUES ('Oxford Trading', 'Ian Smith', 'Oxford', 'UK')
The SQL UPDATE general form
1. UPDATE table-name SET column-name = column-value WHERE condition
Example:
1. UPDATE OrderItem SET Quantity = 2 WHERE Id = 388
The SQL DELETE general form
1. DELETE table-name WHERE condition
Example:
1. DELETE Customer WHERE Email = 'alex@gmail.com'
SQL SELECT Statement
 The SELECT statement retrieves data from a database.
 The data is returned in a table-like structure called a result-set.
 SELECT is the most frequently used action on a database.
The SQL SELECT syntax
The general syntax is:
1. SELECT column-names FROM table-name
USING *
1. SELECT * FROM table-name
SQL SELECT Examples
Problem: List all customers
1. SELECT * FROM Customer
Problem: List the first name, last name, and city of all customers
1. SELECT FirstName, LastName, City FROM Customer
SQL WHERE Clause
 To limit the number of rows use the WHERE clause.
 The WHERE clause filters for rows that meet certain criteria.
 WHERE is followed by a condition that returns either true or false.
 WHERE is used with SELECT, UPDATE, and DELETE.
The SQL WHERE syntax
A WHERE clause with a SELECT statement:
1. SELECT column-names FROM table-name WHERE condition
A WHERE clause with an UPDATE statement:
1. UPDATE table-name SET column-name = value WHERE condition
A WHERE clause with a DELETE statement:
1. DELETE table-name WHERE condition
SQL WHERE Clause Examples
Problem: List the customers in Sweden
1. SELECT Id, FirstName, LastName, City, Country, Phone FROM Customer
WHERE Country = 'Sweden'
Problem: Update the city to Sydney for supplier Pavlova, Ltd.
1. UPDATE Supplier SET City = 'Sydney' WHERE Name = 'Pavlova, Ltd.'
Problem: Delete all products with unit price higher than $50.
1. DELETE FROM Product WHERE UnitPrice > 50
Note: Referential integrity may prevent this deletion.
A better approach may be to discontinue the product, that is, set Is Discontinued
to true.
SQL INSERT INTO Statement
 The INSERT INTO statement is used to add new data to a database.
 The INSERT INTO statement adds a new record to a table.
 INSERT INTO can contain values for some or all of its columns.
 INSERT INTO can be combined with a SELECT to insert records.
The SQL INSERT INTO syntax
The general syntax is:
1. INSERT INTO table-name (column-names) VALUES (values) OR
2. INSERT INTO table-name VALUES (column-names)
SQL INSERT INTO Examples
Problem: Add a record for a new customer
1. INSERT INTO Customer (FirstName, LastName, City, Country, Phone)
VALUES ('Craig', 'Smith', 'New York', 'USA', 1-01-993 2800)
OR
2. INSERT INTO Customer VALUES ('Craig', 'Smith', 'New York', 'USA', 1-01-
993 2800)
Problem: Add a new customer named Anita Coats to the database
1. INSERT INTO Customer (FirstName, LastName) VALUES ('Anita', 'Coats')
The SQL INSERT combined with a SELECT
The general syntax is:
1. INSERT INTO table-name (column-names) SELECT column-names
FROM table-name WHERE condition
SQL INSERT INTO with SELECT Example
Problem: The Bigfoot Brewery supplier is also a customer.
Add a customer record with values from the supplier table.
1. INSERT INTO Customer (FirstName, LastName, City, Country, Phone)
SELECT LEFT (ContactName, CHARINDEX (' ',ContactName) - 1),
SUBSTRING (ContactName, CHARINDEX (' ',ContactName) + 1, 100),
City, Country, Phone FROM Supplier WHERE CompanyName = 'Bigfoot
Breweries'
Note: ContactName is parsed into FirstName and LastName.
Parsing takes place with built-in functions: LEFT, SUBSTRING, and CHARINDEX.
SQL UPDATE Statement
 The UPDATE statement updates data values in a database.
 UPDATE can update one or more records in a table.
 Use the WHERE clause to UPDATE only specific records.
The SQL UPDATE syntax
1. UPDATE table-name SET column-name = value, column-name = value,
To limit the number of records to UPDATE append a WHERE clause:
1. UPDATE table-name SET column-name = value, column-name = value,
WHERE condition
SQL UPDATE Examples
Problem: discontinue all products in the database
1. UPDATE Product SET IsDiscontinued = 1
Note: the value 1 denotes true.
Problem: Discontinue products over $50.
1. UPDATE Product SET IsDiscontinued = 1 WHERE UnitPrice > 50
Note: the value 1 denotes true.
Problem: Discontinue product with Id = 46.
1. UPDATE Product SET IsDiscontinued = 1 WHERE Id = 46
This is a more common scenario in which a single record is updated.
Note: the value 1 denotes true.
Problem: Supplier Norske Meierier (Id = 15) has moved: update their city, phone
and fax.
1. UPDATE Supplier SET City = 'Oslo', Phone = '(0)1-953530',
Fax = '(0)1- 953555' WHERE Id = 15
This is a common scenario in which a single record is updated.
SQL DELETE Statement
 DELETE permanently removes records from a table.
 DELETE can delete one or more records in a table.
 Use the WHERE clause to DELETE only specific records.
The SQL DELETE syntax
The general syntax is:
1. DELETE table-name
To delete specific records append a WHERE clause:
1. DELETE table-name WHERE condition
SQL DELETE Examples
Problem: Delete all products.
1. DELETE Product
Problem: Delete products over $50.
1. DELETE Product WHERE UnitPrice > 50
Problem: Delete customer with Id = 21.
1. DELETE Customer WHERE Id = 21
This is a more common scenario in which a single record is deleted.
SQL ORDER BY Clause
 SELECT returns records in no particular order.
 To ensure a specific order use the ORDER BY clause.
 ORDER BY allows sorting by one or more columns.
 Records can be returned in ascending or descending order.
The SQL ORDER BY syntax
The general syntax is:
1. SELECT column-names FROM table-name WHERE condition ORDER BY
Column-names
SQL ORDER BY Examples
Problem: List all suppliers in alphabetical order
1. SELECT CompanyName, ContactName, City, Country FROM Supplier
ORDER BY CompanyName
The default sort order is ascending, that is, low-high or 1-100
Problem: List all suppliers in reverse alphabetical order
1. SELECT CompanyName, ContactName, City, Country FROM Supplier
ORDER BY CompanyName DESC
The keyword DESC denotes descending, i.e., reverse order 100 - 1.
Problem: List all customers ordered by country, then by city within each country
ordering by one or more columns is possible.
1. SELECT FirstName, LastName, City, Country FROM Customer
ORDER BY Country, City
Problem: List all suppliers in the USA, Japan, and Germany, ordered by city,
then by company name in reverse order
1. SELECT Id, CompanyName, City, Country FROM Supplier WHERE Country
IN ('USA', 'Japan', 'Germany') ORDER BY Country ASC, CompanyName
DESC
This shows that you can order by more than one column.
ASC denotes ascending, but is optional as it is the default sort order.
Problem: Show all orders, sorted by total amount, the largest first, within each
year
1. SELECT Id, OrderDate, CustomerId, TotalAmount FROM [Order] ORDER
BY YEAR(OrderDate) ASC, TotalAmount DESC
Note: DESC means descending, but is optional as it is the default sort order.
[Order] must be bracketed because it also is a key work in SQL.
Notice the year breakpoints: 2012 - 2013 and 2013 - 2014. Each year starts with
the highest TotalAmounts.
This shows that other data types, such as numbers, dates, and bits can also be
sorted.
Note: YEAR is a built-in function which returns the year from a date.
SQL SELECT TOP Statement
 The SELECT TOP statement returns a specified number of records.
 SELECT TOP is useful when working with very large datasets.
 Non SQL Server databases use keywords like LIMIT, OFFSET, and ROWNUM.
The SQL SELECT TOP syntax
The general syntax is:
1. SELECT TOP n column-names FROM table-name
SQL SELECT TOP
Problem: List top 10 most expensive products
1. SELECT TOP 10 Id, ProductName, UnitPrice, Package FROM Product
ORDER BY UnitPrice DESC
SQL OFFSET-FETCH Clause
 OFFSET excludes the first set of records.
 OFFSET can only be used with an ORDER BY clause.
 OFFSET with FETCH NEXT returns a defined window of records.
 OFFSET with FETCH NEXT is great for building pagination support.
The SQL ORDER BY OFFSET syntax
The general syntax to exclude first n records is:
1. SELECT column-names FROM table-name ORDER BY column-names
OFFSET n ROWS
To exclude first n records and return only the next m records:
1. SELECT column-names FROM table-name ORDER BY column-names
OFFSET n ROWS FETCH NEXT m ROWS ONLY
This will return only record (n + 1) to (n + 1 + m). See example below.
SQL OFFSET-FETCH Examples
Problem: Get all but the 10 most expensive products sorted by price
1. SELECT Id, ProductName, UnitPrice, Package FROM Product
ORDER BY UnitPrice DESC OFFSET 10 ROWS
Problem: Get the 10th to 15th most expensive products sorted by price
1. SELECT Id, ProductName, UnitPrice, Package FROM Product
ORDER BY UnitPrice DESC OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY
SQL SELECT DISTINCT Statement
 SELECT DISTINCT returns only distinct (different) values.
 SELECT DISTINCT eliminates duplicate records from the results.
 DISTINCT can be used with aggregates: COUNT, AVG, MAX, etc.
 DISTINCT operates on a single column. DISTINCT for multiple columns is not supported.
The SQL SELECT DISTINCT syntax
The general syntax is:
1. SELECT DISTINCT column-name FROM table-name
Can be used with COUNT and other aggregates
1. SELECT COUNT (DISTINCT column-name)FROM table-name
SQL SELECT Examples
Problem: List all supplier countries in alphabetical order.
1. SELECT DISTINCT Country FROM Supplier ORDER BY
COUNTRY
Problem: List the number of supplier countries
1. SELECT COUNT (DISTINCT Country) FROM Supplier
SQL SELECT MIN, MAX Statement
 SELECT MIN returns the minimum value for a column.
 SELECT MAX returns the maximum value for a column.
The SQL SELECT MIN and MAX syntax
The general MIN syntax is:
1. SELECT MIN(column-name) FROM table-name
The general MAX syntax is:
1. SELECT MAX(column-name) FROM table-name
SQL SELECT MAX and MIN Examples
Problem: Find the largest order placed in 2014
1. SELECT MAX(TotalAmount) FROM [Order] WHERE YEAR(OrderDate) =
2014
Problem: Find the last order date in 2013
1. SELECT MAX(OrderDate) FROM [Order] WHERE YEAR(OrderDate) =
2013 MIN and MAX can also be used with numeric and date types.
SQL SELECT COUNT, SUM, AVG
 SELECT COUNT returns a count of the number of data values.
 SELECT SUM returns the sum of the data values.
 SELECT AVG returns the average of the data values.
The SQL SELECT COUNT, SUM, and AVG syntax
The general COUNT syntax is:
1. SELECT COUNT(column-name) FROM table-name
The general SUM syntax is:
1. SELECT SUM(column-name)FROM table-name
The general AVG syntax is:
1. SELECT AVG(column-name)FROM table-name
SQL SELECT COUNT, SUM, and AVG Examples
Problem: Find the number of customers
1. SELECT COUNT(Id)FROM Customer
Problem: Compute the total amount sold in 2013
1. SELECT SUM(TotalAmount) FROM [Order] WHERE YEAR(OrderDate) =
2013
Problem: Compute the average size of all orders
1. SELECT AVG(TotalAmount) FROM [Order]
SQL WHERE AND, OR, NOT Clause
 WHERE conditions can be combined with AND, OR, and NOT.
 A WHERE clause with AND requires that two conditions are true.
 A WHERE clause with OR requires that one of two conditions is true.
 A WHERE clause with NOT negates the specified condition.
The WHERE with AND, OR, NOT syntax
A WHERE clause with AND:
1. SELECT column-names FROM table-name WHERE condition1 AND
condition2
A WHERE clause with OR:
1. UPDATE table-name SET column-name = value WHERE condition1 OR
condition2
A WHERE clause with NOT:
1. DELETE table-name WHERE NOT condition
SQL WHERE with AND, OR, and NOT Examples
Problem: Get customer named Thomas Hardy
1. SELECT Id, FirstName, LastName, City, Country FROM Customer
WHERE FirstName = 'Thomas' AND LastName = 'Hardy'
Problem: List all customers from Spain or France
1. SELECT Id, FirstName, LastName, City, Country FROM Customer
WHERE Country = 'Spain' OR Country = 'France'
Problem: List all customers that are not from the USA
1. SELECT Id, FirstName, LastName, City, Country FROM Customer
WHERE NOT Country = 'USA'
Problem: List all orders that not between $50 and $15000
1. SELECT Id, OrderDate, CustomerId, TotalAmount FROM [Order]
WHERE NOT (TotalAmount >= 50 AND TotalAmount <= 15000) ORDER BY
TotalAmount DESC
SQL WHERE BETWEEN Clause
 WHERE BETWEEN returns values that fall within a given range.
 WHERE BETWEEN is a shorthand for >= AND <=.
 BETWEEN operators is inclusive: begin and end values are included. The
definitive guide for data professionals
The SQL WHERE BETWEEN syntax
The general syntax is:
1. SELECT column-names FROM table-name WHERE column-name
BETWEEN value1 AND value2
SQL WHERE BETWEEN Examples
Problem: List all products between $10 and $20
1. SELECT Id, ProductName, UnitPrice FROM Product WHERE UnitPrice
BETWEEN 10 AND 20 ORDER BY UnitPrice
Problem: List all products not between $10 and $100 sorted by price.
1. SELECT Id, ProductName, UnitPrice FROM Product WHERE UnitPrice
NOT BETWEEN 5 AND 100 ORDER BY UnitPrice
Problem: Get the number of orders and amount sold between Jan 1, 2013 and Jan
31, 2013.
1. SELECT COUNT(Id), SUM(TotalAmount)FROM [Order] WHERE OrderDate
BETWEEN '1/1/2013' AND '1/31/2013'
SQL WHERE IN Clause
 WHERE IN returns values that matches values in a list or sub query.
 WHERE IN is a shorthand for multiple OR conditions.
The SQL WHERE IN syntax
The general syntax is:
1. SELECT column-names FROM table-name WHERE column-name IN
(values)
SQL WHERE IN Examples
Problem: List all suppliers from the USA, UK, OR Japan
1. SELECT Id, CompanyName, City, Country FROM Supplier WHERE Country
IN ('USA', 'UK', and ‘Japan’)
Problem: List all products that are not exactly $10, $20, $30, $40, or $50
1. SELECT Id, ProductName, UnitPrice FROM Product WHERE UnitPrice
NOT IN (10, 20, 30, 40, 50)
Problem: List all customers that are from the same countries as the suppliers.
1. SELECT Id, FirstName, LastName, Country FROM Customer WHERE
Country IN (SELECT Country FROM Supplier)
SQL WHERE LIKE Statement
 WHERE LIKE determines if a character string matches a pattern.
 Use WHERE LIKE when only a fragment of a text value is known.
 WHERE LIKE supports two wildcard match options: % and _.
The SQL WHERE LIKE syntax
The general syntax is:
1. SELECT column-names FROM table-name WHERE column-
name LIKE value
Optional Wildcard characters allowed in 'value' are % (percent) and _
(underscore).
A % matches any string with zero or more characters.
An _ matches any single character.
SQL WHERE LIKE Examples
Problem: List all products with names that start with 'Ca'
1. SELECT Id, ProductName, UnitPrice, Package FROM Product WHERE
ProductName LIKE 'Ca%'
Problem: List all products that start with 'Cha' or 'Chan' and have one more
character.
1. SELECT Id, ProductName, UnitPrice, Package FROM Product
WHERE ProductName LIKE 'Cha_' OR ProductName LIKE 'Chan_'
SQL IS NULL Clause
 NULL is a special value that signifies 'no value'.
 Comparing a column to NULL using the = operator is undefined.
 Instead, use WHERE IS NULL or WHERE IS NOT NULL.
The SQL WHERE IS NULL syntax
The general syntax is:
1. SELECT column-names FROM table-name WHERE column-name IS NULL
The general not null syntax is:
1. SELECT column-names FROM table-name WHERE column-name IS NOT
NULL
SQL WHERE IS NULL Examples
Problem: List all suppliers that have no fax number
1. SELECT Id, CompanyName, Phone, Fax FROM Supplier WHERE Fax IS
NULL
Problem: List all suppliers that do have a fax number
1. SELECT Id, CompanyName, Phone, Fax FROM Supplier WHERE Fax IS
NOT NULL
SQL GROUP BY Clause
 The GROUP BY clause groups records into summary rows.
 GROUP BY returns one records for each group.
 GROUP BY typically also involves aggregates: COUNT, MAX, SUM, AVG, etc.
 GROUP BY can group by one or more columns.
The SQL GROUP BY syntax
The general syntax is:
1. SELECT column-names FROM table-name WHERE condition GROUP BY
column-names
The general syntax with ORDER BY is:
1. SELECT column-names FROM table-name WHERE condition GROUP BY
column-names ORDER BY column-names
SQL GROUP BY Examples
Problem: List the number of customers in each country
1. SELECT COUNT(Id), Country FROM Customer GROUP BY Country
Problem: List the number of customers in each country sorted high to low
1. SELECT COUNT(Id), Country FROM Customer GROUP BY Country
ORDER BY COUNT(Id) DESC
Problem: List the total amount ordered for each customer
SELECT SUM(O.TotalPrice), C.FirstName, C.LastName FROM [Order] O
JOIN Customer C ON O.CustomerId = C.Id GROUP BY C.FirstName,
C.LastName ORDER BY SUM(O.TotalPrice) DESC
This query uses a JOIN with Customer to obtain customer names
SQL HAVING Clause
 HAVING filters records that work on summarized GROUP BY results.
 HAVING applies to summarized group records, whereas WHERE applies to
individual records.
 Only the groups that meet the HAVING criteria will be returned.
 HAVING requires that a GROUP BY clause is present.
 WHERE and HAVING can be in the same query.
The SQL HAVING syntax
The general syntax is:
1. SELECT column-names FROM table-name WHERE condition
GROUP BY column-names HAVING condition
The general syntax with ORDER BY is:
1. SELECT column-names FROM table-name WHERE condition GROUP BY
column- names HAVING condition ORDER BY column-names
SQL GROUP BY Examples
Problem: List the number of customers in each country. Only include countries
with more than 10 customers.
1. SELECT COUNT(Id), Country FROM Customer GROUP BY Country
Problem: List the number of customers in each country, except the USA, sorted
high to low.
Only include countries with 9 or more customers.
1. SELECT COUNT(Id), Country FROM Customer WHERE Country <> 'USA'
GROUP BY Country HAVING COUNT (Id) >= 9 ORDER BY COUNT(Id) DESC
Problem: List all customer with average orders between $1000 and $1200.
SELECT AVG(TotalAmount), FirstName, LastName FROM [Order] O JOIN
Customer C ON O.CustomerId = C.Id GROUP BY FirstName, LastName
HAVING AVG(TotalAmount) BETWEEN 1000 AND 1200
SQLAlias
 An Alias is a shorthand for a table or column name.
 Aliases reduce the amount of typing required to enter a query.
 Complex queries with aliases are generally easier to read.
 Aliases are useful with JOINs and aggregates: SUM, COUNT, etc.
 An Alias only exists for the duration of the query.
The SQL Alias syntax
The general syntax is:
1. SELECT column-name AS alias-name FROM table-name alias-name
WHERE condition
SQL Alias Examples
Problem: List total customers in each country.
Display results with easy to understand column headers.
1. SELECT COUNT (C.Id) AS TotalCustomers, C.Country AS Nation FROM
Customer C GROUP BY C.Country TotalCustomers and Nation are column
aliases.
The table alias (C) in this example is not particularly useful.
Problem: List the total amount ordered by customer
with easy to read column headers
1. SELECT C.Id AS Identifier, C.LastName + ', ' + C.FirstName AS CustomerName,
SUM(O.TotalAmount) AS TotalSpent FROM [Order] O JOIN Customer C ON
O.CustomerId = C.Id GROUP BY C.Id, C.LastName + ', ' + C.FirstName ORDER BY
TotalSpent DESC
The aliases significantly simplify writing the JOIN and ORDER BY clauses.
The C alias in C.Id helps identify the Customer Id rather then the Order Id.
SQL JOIN
 A SQL JOIN combines records from two tables.
 A JOIN locates related column values in the two tables.
 A query can contain zero, one, or multiple JOIN operations.
 INNER JOIN is the same as JOIN; the keyword INNER is optional.
Different types of JOINs
 (INNER) JOIN: Select records that have matching values in both tables.
 LEFT (OUTER) JOIN: Select records from the first (left-most) table with
matching right table records.
 RIGHT (OUTER) JOIN: Select records from the second (right-most) table with
matching left table records.
 FULL (OUTER) JOIN: Selects all records that match either left or right table
records.
All INNER and OUTER keywords are optional.
Details about the differences between these JOINs are available in subsequent tutorial pages.
The SQL JOIN syntax
The general syntax is:
1. SELECT column-names FROM table-name1 JOIN table-name2 ON
column-name1 = column-name2 WHERE condition
The general syntax with INNER is:
1. SELECT column-names FROM table-name1 INNER JOIN table-name2
ON column-name1 = column-name2 WHERE condition
Note: The INNER keyword is optional: it is the default as well as the most common
only used JOIN operation.
SQL JOIN Examples
Problem: List all orders with customer information
1. SELECT OrderNumber, TotalAmount, FirstName, LastName, City,
Country FROM [Order] JOIN Customer ON [Order].CustomerId =
Customer.Id
In this example using table aliases for [Order] and Customer might have been
useful.
Problem: List all orders with product names, quantities, and prices
1. SELECT O.OrderNumber, CONVERT(date,O.OrderDate) AS Date,
P.ProductName, I.Quantity, I.UnitPrice FROM [Order] O JOIN OrderItem I
ON O.Id = I.OrderId JOIN Product P ON P.Id = I.ProductId ORDER BY
O.OrderNumber
This query performs two JOIN operations with 3 tables.
The O, I, and P are table aliases. Date is a column alias.
SQL LEFT JOIN
 LEFT JOIN performs a join starting with the first (left-most) table and then
any matching second (right-most) table records.
 LEFT JOIN and LEFT OUTER JOIN are the same.
The SQL LEFT JOIN syntax
The general syntax is:
1. SELECT column-names FROM table-name1 LEFT JOIN table-name2
ON column-name1 = column-name2 WHERE condition
SQL LEFT JOIN Example
The general LEFT OUTER JOIN syntax is:
SELECT OrderNumber, TotalAmount, FirstName, LastName, City, Country
FROM Customer C LEFT JOIN [Order] O ON O.CustomerId = C.Id ORDER BY
TotalAmount
This will list all customers, whether they placed any order or not.
The ORDER BY TotalAmount shows the customers without orders first
(i.e.TotalMount is NULL).
SQL RIGHT JOIN
 RIGHT JOIN performs a join starting with the second (right-most) table and
then any matching first (left-most) table records.
 RIGHT JOIN and RIGHT OUTER JOIN are the same.
The SQL RIGHT JOIN syntax
The general syntax is:
1. SELECT column-names FROM table-name1 RIGHT JOIN table-name2
ON column-name1 = column-name2 WHERE condition
The general RIGHT OUTER JOIN syntax is:
1. SELECT column-names FROM table-name1 RIGHT OUTER JOIN table-
name2 ON column-name1 = column-name2 WHERE condition
SQL RIGHT JOIN Example
Problem: List customers that have not placed orders
1. SELECT TotalAmount, FirstName, LastName, City, Country FROM [Order]
O RIGHT JOIN Customer C ON O.CustomerId = C.Id WHERE TotalAmount IS
NULL
This returns customers that, when joined, have no matching order.
SQL FULL JOIN
 FULL JOIN returns all matching records from both tables whether the other
table matches or not.
 FULL JOIN can potentially return very large datasets.
 FULL JOIN and FULL OUTER JOIN are the same.
The SQL FULL JOIN syntax
The general syntax is:
1. SELECT column-names FROM table-name1 FULL JOIN table-name2
ON column-name1 = column-name2 WHERE condition
The general FULL OUTER JOIN syntax is:
1. SELECT column-names FROM table-name1 FULL OUTER JOIN table-
name2 ON column-name1 = column-name2 WHERE condition
SQL FULL JOIN Examples
Problem: Match all customers and suppliers by country
1. SELECT C.FirstName, C.LastName, C.Country AS CustomerCountry,
S.Country AS SupplierCountry, S.CompanyName FROM Customer C FULL
JOIN Supplier S ON C.Country = S.Country ORDER BY C.Country, S.Country
This returns suppliers that have no customers in their country,
and customers that have no suppliers in their country,
and customers and suppliers that are from the same country.
SQL SELF JOIN
 A self JOIN occurs when a table takes a 'selfie'.
 A self JOIN is a regular join but the table is joined with itself.
 This can be useful when modeling hierarchies.
 They are also useful for comparisons within a table
The SQL Self JOIN syntax
The general syntax is:
1. SELECT column-names FROM table-name T1 JOIN table-name T2 WHERE
condition
T1 and T2 are different table aliases for the same table
SQL Self JOIN Examples
Problem: Match customers that are from the same city and country
1. SELECT B.FirstName AS FirstName1, B.LastName AS LastName1,
A.FirstName AS FirstName2, A.LastName AS LastName2,
B.City, B.Country FROM Customer A, Customer B WHERE A.Id <> B.Id
AND A.City = B.City AND A.Country = B.Country ORDER BY A.Country
A and B are aliases for the same Customer table.
SQL UNION Clause
 UNION combines the result sets of two queries.
 Column data types in the two queries must match.
 UNION combines by column position rather than column name.
The SQL UNION syntax
The general syntax is:
1. SELECT column-names FROM table-name
UNION
SELECT column-names FROM table-name
SQL UNION Examples
Problem: List all contacts, i.e., suppliers and customers.
1. SELECT 'Customer' As Type, FirstName + ' ' + LastName AS ContactName,
City, Country, Phone FROM Customer
UNION
SELECT 'Supplier', ContactName, City, Country, Phone FROM Supplier
This is a simple example in which the table alias would be useful
SQL Subqueries
 A subquery is a SQL query within a query.
 Subqueries are nested queries that provide data to the enclosing query.
 Subqueries can return individual values or a list of records
 Subqueries must be enclosed with parenthesis
The SQL subquery syntax
There is no general syntax;
subqueries are regular queries placed inside parenthesis.
Subqueries can be used in different ways and at different locations inside a query:
Here is an subquery with the IN operator
1. SELECT column-names FROM table-name1 WHERE value IN (SELECT
column-name FROM table-name2 WHERE condition)
Subqueries can also assign column values for each record:
1. SELECT column1 = (SELECT column-name FROM table-
name WHERE condition),column-names FROM table-name
WEHRE condition
SQL Subquery Examples
Problem: List products with order quantities greater than 100.
1. SELECT ProductName FROM Product WHERE Id IN (SELECT ProductId
FROM OrderItem WHERE Quantity > 100)
SQL Subquery Examples
Problem: List all customers with their total number of orders
1. SELECT FirstName, LastName,OrderCount = (SELECT COUNT(O.Id) FROM
[Order] O WHERE O.CustomerId = C.Id)FROM Customer C
This is a correlated subquery because the subquery references the enclosing
query (i.e. the C.Id in the WHERE clause).
SQL WHERE ANY, ALL Clause
 ANY and ALL keywords are used with a WHERE or HAVING clause.
 ANY and ALL operate on subqueries that return multiple values.
 ANY returns true if any of the subquery values meet the condition.
 ALL returns true if all of the subquery values meet the condition.
The SQL WHERE ANY and ALL syntax
The general ANY syntax is:
1. SELECT column-names FROM table-name WHERE column-name
operator ANY (SELECT column-name FROM table-name WHERE condition)
The general ALL syntax is:
1. SELECT column-names FROM table-name WHERE column-name
operator ALL (SELECT column-name FROM table-name WHERE condition)
SQL ANY Example
Problem: Which products were sold by the unit (i.e. quantity = 1)
1. SELECT ProductName FROM Product WHERE Id = ANY (SELECT ProductId
FROM OrderItem WHERE Quantity = 1)
SQL ALL Example
Problem: List customers who placed orders that are
larger than the average of each customer order
1. SELECT DISTINCT FirstName + ' ' + LastName as CustomerName
FROM Customer, [Order] WHERE Customer.Id = [Order].CustomerId
AND TotalAmount > ALL (SELECT AVG(TotalAmount) FROM [Order]
GROUP BY CustomerId)
SQL WHERE EXISTS Statement
 WHERE EXISTS tests for the existence of any records in a subquery.
 EXISTS returns true if the subquery returns one or more records.
 EXISTS is commonly used with correlated subqueries.
The SQL EXISTS syntax
The general syntax is:
1. SELECT column-names FROM table-name WHERE EXISTS
(SELECT column- name FROM table-name WHERE condition)
SQL EXISTS Example
Problem: Find suppliers with products over $100.
1. SELECT CompanyName FROM Supplier WHERE EXISTS (SELECT
ProductName FROM Product WHERE SupplierId = Supplier.Id
AND UnitPrice > 100)
This is a correlated subquery because the subquery references the enclosing
query (with Supplier.Id).
SQL SELECT INTO Statement
 SELECT INTO copies data from one table into a new table.
 SELECT INTO creates a new table located in the default file group.
The SQL SELECT INTO syntax
The general syntax is:
1. SELECT column-names INTO new-table-name FROM table-name
WHERE EXISTS (SELECT column-name FROM table-name WHERE
condition)
The new table will have column names as specified in the query.
SQL SELECT INTO Example
Problem: Copy all suppliers from USA to a new SupplierUSA table.
1. SELECT * INTO SupplierUSA FROM Supplier
WHERE Country = 'USA'
SQL INSERT INTO SELECT Statement
 INSERT INTO SELECT copies data from one table to another table.
 INSERT INTO SELECT requires that data types in source and target tables
match.
The SQL INSERT INTO SELECT syntax
The general syntax is:
1. INSERT INTO table-name (column-names)
SELECT column-names FROM table-name WHERE condition
SQL INSERT SELECT INTO
Problem: Copy all Canadian suppliers into the Customer table
INSERT INTO Customer (FirstName, LastName, City, Country, Phone)
SELECT LEFT(ContactName, CHARINDEX(' ',ContactName) - 1) AS FirstName,
SUBSTRING(ContactName, CHARINDEX(' ',ContactName) + 1, 100) AS LastName,
City, Country, Phone FROM Supplier WHERE Country = 'Canada'
LEFT, CHARINDEX, and SUBSTRING are built-in functions.
These are the two new Customer records
SQL Injection
 SQL Injection is a code injection technique.
 It is the placement of malicious code in SQL strings.
 SQL Injection is one of the most common web hacking techniques.
 These attacks only work with apps that internally use SQL.
SQL Keywords
 SQL Server uses reserved words for database operations.
 Reserved keywords are part of the SQL Server T-SQL grammar.
 SQL Server has claimed current and future reserved words.
 Keywords can be used as identifiers by placing them between [].
Current T-SQL Keywords
ADD EXCEPT PERCENT
ALL EXEC PLAN
ALTER EXECUTE PRECISION
AND EXISTS PRIMARY
ANY EXIT PRINT
AS FETCH PROC
ASC FILE PROCEDURE
AUTHORIZATION FILLFACTOR PUBLIC
BACKUP FOR RAISERROR
BEGIN FOREIGN READ
BETWEEN FREETEXT READTEXT
BREAK FREETEXTTABLE RECONFIGURE
BROWSE FROM REFERENCES
BULK FULL REPLICATION
BY FUNCTION RESTORE
CASCADE GOTO RESTRICT
CASE GRANT RETURN
CHECK GROUP REVOKE
CHECKPOINT HAVING RIGHT
CLOSE HOLDLOCK ROLLBACK
CLUSTERED IDENTITY ROWCOUNT
COALESCE IDENTITY_INSERT ROWGUIDCOL
COLLATE IDENTITYCOL RULE
COLUMN IF SAVE
COMMIT IN SCHEMA
COMPUTE INDEX SELECT
CONSTRAINT INNER SESSION_USER
CONTAINS INSERT SET
CONTAINSTABLE INTERSECT SETUSER
CONTINUE INTO SHUTDOWN
CONVERT IS SOME
CREATE JOIN STATISTICS
CROSS KEY SYSTEM_USER
CURRENT KILL TABLE
CURRENT_DATE LEFT TEXTSIZE
CURRENT_TIME LIKE THEN
CURRENT_TIMESTAMP LINENO TO
CURRENT_USER LOAD TOP
CURSOR NATIONAL TRAN
DATABASE NOCHECK TRANSACTION
DBCC NONCLUSTERED TRIGGER
DEALLOCATE NOT TRUNCATE
DECLARE NULL TSEQUAL
DEFAULT NULLIF UNION
DELETE OF UNIQUE
DENY OFF UPDATE
DESC OFFSETS UPDATETEXT
DISK ON USE
DISTINCT OPEN USER
DISTRIBUTED OPENDATASOURCE VALUES
DOUBLE OPENQUERY VARYING
DROP OPENROWSET VIEW
DUMMY OPENXML WAITFOR
DUMP OPTION WHEN
ELSE OR WHERE
END ORDER WHILE
ERRLVL OUTER WITH
ESCAPE OVER WRITETEXT
Future T-SQL Keywords
ABSOLUTE FOUND PRESERVE
ACTION FREE PRIOR
ADMIN GENERAL PRIVILEGES
AFTER GET READS
AGGREGATE GLOBAL REAL
ALIAS GO RECURSIVE
ALLOCATE GROUPING REF
ARE HOST REFERENCING
ARRAY HOUR RELATIVE
ASSERTION IGNORE RESULT
AT IMMEDIATE RETURNS
BEFORE INDICATOR ROLE
BINARY INITIALIZE ROLLUP
BIT INITIALLY ROUTINE
BLOB INOUT ROW
BOOLEAN INPUT ROWS
BOTH INT SAVEPOINT
BREADTH INTEGER SCROLL
CALL INTERVAL SCOPE
CASCADED ISOLATION SEARCH
CAST ITERATE SECOND
CATALOG LANGUAGE SECTION
CHAR LARGE SEQUENCE
CHARACTER LAST SESSION
CLASS LATERAL SETS
CLOB LEADING SIZE
COLLATION LESS SMALLINT
COMPLETION LEVEL SPACE
CONNECT LIMIT SPECIFIC
CONNECTION LOCAL SPECIFICTYPE
CONSTRAINTS LOCALTIME SQL
CONSTRUCTOR LOCALTIMESTAMP SQLEXCEPTION
CORRESPONDING LOCATOR SQLSTATE
CUBE MAP SQLWARNING
CURRENT_PATH MATCH START
CURRENT_ROLE MINUTE STATE
CYCLE MODIFIES STATEMENT
DATA MODIFY STATIC
DATE MODULE STRUCTURE
DAY MONTH TEMPORARY
DEC NAMES TERMINATE
DECIMAL NATURAL THAN
DEFERRABLE NCHAR TIME
DEFERRED NCLOB TIMESTAMP
DEPTH NEW TIMEZONE_HOUR
DEREF NEXT TIMEZONE_MINUTE
DESCRIBE NO TRAILING
DESCRIPTOR NONE TRANSLATION
DESTROY NUMERIC TREAT
DESTRUCTOR OBJECT TRUE
DETERMINISTIC OLD UNDER
DICTIONARY ONLY UNKNOWN
DIAGNOSTICS OPERATION UNNEST
DISCONNECT ORDINALITY USAGE
DOMAIN OUT USING
DYNAMIC OUTPUT VALUE
EACH PAD VARCHAR
END-EXEC PARAMETER VARIABLE
EQUALS PARAMETERS WHENEVER
EVERY PARTIAL WITHOUT
EXCEPTION PATH WORK
EXTERNAL POSTFIX WRITE
FALSE PREFIX YEAR
FIRST PREORDER ZONE
FLOAT PREPARE
Sql

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
BIS05 Introduction to SQL
BIS05 Introduction to SQLBIS05 Introduction to SQL
BIS05 Introduction to SQL
 
Sql wksht-6
Sql wksht-6Sql wksht-6
Sql wksht-6
 
Introduction to sql
Introduction to sqlIntroduction to sql
Introduction to sql
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
SQL
SQLSQL
SQL
 
Microsoft MCSA 70-457 it exams dumps
Microsoft MCSA 70-457 it exams dumpsMicrosoft MCSA 70-457 it exams dumps
Microsoft MCSA 70-457 it exams dumps
 
Sql
SqlSql
Sql
 
Sql for biggner
Sql for biggnerSql for biggner
Sql for biggner
 
introdution to SQL and SQL functions
introdution to SQL and SQL functionsintrodution to SQL and SQL functions
introdution to SQL and SQL functions
 
Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)
 
Sql intro
Sql introSql intro
Sql intro
 
Sql wksht-2
Sql wksht-2Sql wksht-2
Sql wksht-2
 
Sql wksht-3
Sql wksht-3Sql wksht-3
Sql wksht-3
 
Sql ch 5
Sql ch 5Sql ch 5
Sql ch 5
 
Advanced SQL Webinar
Advanced SQL WebinarAdvanced SQL Webinar
Advanced SQL Webinar
 
Basic SQL
Basic SQLBasic SQL
Basic SQL
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
 
SQL
SQLSQL
SQL
 
DDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using OracleDDL(Data defination Language ) Using Oracle
DDL(Data defination Language ) Using Oracle
 

Ähnlich wie Sql

Ähnlich wie Sql (20)

SQL
SQLSQL
SQL
 
Database Architecture and Basic Concepts
Database Architecture and Basic ConceptsDatabase Architecture and Basic Concepts
Database Architecture and Basic Concepts
 
SQL Query
SQL QuerySQL Query
SQL Query
 
Sql 2006
Sql 2006Sql 2006
Sql 2006
 
Query
QueryQuery
Query
 
SQL.ppt
SQL.pptSQL.ppt
SQL.ppt
 
ORACLE PL/SQL TUTORIALS - OVERVIEW - SQL COMMANDS
ORACLE PL/SQL TUTORIALS - OVERVIEW - SQL COMMANDSORACLE PL/SQL TUTORIALS - OVERVIEW - SQL COMMANDS
ORACLE PL/SQL TUTORIALS - OVERVIEW - SQL COMMANDS
 
SQLSERVERQUERIES.pptx
SQLSERVERQUERIES.pptxSQLSERVERQUERIES.pptx
SQLSERVERQUERIES.pptx
 
SQL Beginners anishurrehman.cloud.pdf
SQL Beginners anishurrehman.cloud.pdfSQL Beginners anishurrehman.cloud.pdf
SQL Beginners anishurrehman.cloud.pdf
 
Learning sql from w3schools
Learning sql from w3schoolsLearning sql from w3schools
Learning sql from w3schools
 
Sql
SqlSql
Sql
 
Creating database using sql commands
Creating database using sql commandsCreating database using sql commands
Creating database using sql commands
 
Sql
SqlSql
Sql
 
DBMS
DBMSDBMS
DBMS
 
Introduction to sql new
Introduction to sql newIntroduction to sql new
Introduction to sql new
 
Hira
HiraHira
Hira
 
Sql
SqlSql
Sql
 
SQL Fundamentals
SQL FundamentalsSQL Fundamentals
SQL Fundamentals
 
SQL report
SQL reportSQL report
SQL report
 
Chapter 4 Structured Query Language
Chapter 4 Structured Query LanguageChapter 4 Structured Query Language
Chapter 4 Structured Query Language
 

Kürzlich hochgeladen

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...KokoStevan
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfSanaAli374401
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 

Kürzlich hochgeladen (20)

Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 

Sql

  • 2. SQL Tutorial: Introduction What is SQL?  SQL is a language used to retrieve and manipulate data in a RDMS.  SQL stands for Structured Query Language. What is a Database?  A database is a place to store data.  A relational database system (RDMS) stores data in tables. Relational Database Tables A relational database stores data in tables. Each table has a number of rows and columns. The table below has 4 rows and 3 columns. SQL and Relational Databases A relational database contains tables which store data that is related in some way. SQL is the language that allows retrieval and manipulation of table data in a relational database. The database below has 2 tables: one with data on Users and another with data on Products.
  • 3. . Example database This tutorial uses a database which is a modernized version of Microsoft's Northwind database. Northwind is a fictitious store that sells specialty food products from all over the world. The database has 5 tables. Below are an Entity Relationship Diagram (ERD) which shows the tables and their relationships.
  • 4. SQL Syntax  The syntax of a language describes the language elements.  SQL statements are somewhat like simple English sentences.  Keywords include SELECT, UPDATE, WHERE, ORDER BY, etc.  ANSI Standard SQL is the lingua franca for relational databases. The SQL Syntax SQL was designed to be entered on a console and results would display back to a screen. Today, SQL is mostly used by programmers who use SQL inside their language to build applications that access data in a database. Four fundamental operations that apply to any database are: 1. Read the data -- SELECT 2. Insert new data -- INSERT 3. Update existing data -- UPDATE 4. Remove data -- DELETE Collectively these are referred to as CRUD (Create, Read, Update, and Delete). The general form for each of these 4 operations in SQL is presented next. The SQL SELECT general form 1. SELECT column-names FROM table-name WHERE condition ORDER BY sort-order Example: 1. SELECT FirstName, LastName, City, Country FROM Customer WHERE City = 'Paris' ORDER BY LastName The SQL INSERT general form 1. INSERT table-name (column-names) VALUES (column-values) Example: 1. INSERT Supplier (Name, ContactName, City, Country) VALUES ('Oxford Trading', 'Ian Smith', 'Oxford', 'UK')
  • 5. The SQL UPDATE general form 1. UPDATE table-name SET column-name = column-value WHERE condition Example: 1. UPDATE OrderItem SET Quantity = 2 WHERE Id = 388 The SQL DELETE general form 1. DELETE table-name WHERE condition Example: 1. DELETE Customer WHERE Email = 'alex@gmail.com' SQL SELECT Statement  The SELECT statement retrieves data from a database.  The data is returned in a table-like structure called a result-set.  SELECT is the most frequently used action on a database. The SQL SELECT syntax The general syntax is: 1. SELECT column-names FROM table-name USING * 1. SELECT * FROM table-name SQL SELECT Examples Problem: List all customers 1. SELECT * FROM Customer Problem: List the first name, last name, and city of all customers 1. SELECT FirstName, LastName, City FROM Customer
  • 6. SQL WHERE Clause  To limit the number of rows use the WHERE clause.  The WHERE clause filters for rows that meet certain criteria.  WHERE is followed by a condition that returns either true or false.  WHERE is used with SELECT, UPDATE, and DELETE. The SQL WHERE syntax A WHERE clause with a SELECT statement: 1. SELECT column-names FROM table-name WHERE condition A WHERE clause with an UPDATE statement: 1. UPDATE table-name SET column-name = value WHERE condition A WHERE clause with a DELETE statement: 1. DELETE table-name WHERE condition SQL WHERE Clause Examples Problem: List the customers in Sweden 1. SELECT Id, FirstName, LastName, City, Country, Phone FROM Customer WHERE Country = 'Sweden' Problem: Update the city to Sydney for supplier Pavlova, Ltd. 1. UPDATE Supplier SET City = 'Sydney' WHERE Name = 'Pavlova, Ltd.' Problem: Delete all products with unit price higher than $50. 1. DELETE FROM Product WHERE UnitPrice > 50 Note: Referential integrity may prevent this deletion. A better approach may be to discontinue the product, that is, set Is Discontinued to true.
  • 7. SQL INSERT INTO Statement  The INSERT INTO statement is used to add new data to a database.  The INSERT INTO statement adds a new record to a table.  INSERT INTO can contain values for some or all of its columns.  INSERT INTO can be combined with a SELECT to insert records. The SQL INSERT INTO syntax The general syntax is: 1. INSERT INTO table-name (column-names) VALUES (values) OR 2. INSERT INTO table-name VALUES (column-names) SQL INSERT INTO Examples Problem: Add a record for a new customer 1. INSERT INTO Customer (FirstName, LastName, City, Country, Phone) VALUES ('Craig', 'Smith', 'New York', 'USA', 1-01-993 2800) OR 2. INSERT INTO Customer VALUES ('Craig', 'Smith', 'New York', 'USA', 1-01- 993 2800) Problem: Add a new customer named Anita Coats to the database 1. INSERT INTO Customer (FirstName, LastName) VALUES ('Anita', 'Coats') The SQL INSERT combined with a SELECT The general syntax is: 1. INSERT INTO table-name (column-names) SELECT column-names FROM table-name WHERE condition SQL INSERT INTO with SELECT Example Problem: The Bigfoot Brewery supplier is also a customer. Add a customer record with values from the supplier table. 1. INSERT INTO Customer (FirstName, LastName, City, Country, Phone) SELECT LEFT (ContactName, CHARINDEX (' ',ContactName) - 1), SUBSTRING (ContactName, CHARINDEX (' ',ContactName) + 1, 100), City, Country, Phone FROM Supplier WHERE CompanyName = 'Bigfoot Breweries'
  • 8. Note: ContactName is parsed into FirstName and LastName. Parsing takes place with built-in functions: LEFT, SUBSTRING, and CHARINDEX. SQL UPDATE Statement  The UPDATE statement updates data values in a database.  UPDATE can update one or more records in a table.  Use the WHERE clause to UPDATE only specific records. The SQL UPDATE syntax 1. UPDATE table-name SET column-name = value, column-name = value, To limit the number of records to UPDATE append a WHERE clause: 1. UPDATE table-name SET column-name = value, column-name = value, WHERE condition SQL UPDATE Examples Problem: discontinue all products in the database 1. UPDATE Product SET IsDiscontinued = 1 Note: the value 1 denotes true. Problem: Discontinue products over $50. 1. UPDATE Product SET IsDiscontinued = 1 WHERE UnitPrice > 50 Note: the value 1 denotes true. Problem: Discontinue product with Id = 46. 1. UPDATE Product SET IsDiscontinued = 1 WHERE Id = 46 This is a more common scenario in which a single record is updated. Note: the value 1 denotes true. Problem: Supplier Norske Meierier (Id = 15) has moved: update their city, phone and fax. 1. UPDATE Supplier SET City = 'Oslo', Phone = '(0)1-953530', Fax = '(0)1- 953555' WHERE Id = 15 This is a common scenario in which a single record is updated.
  • 9. SQL DELETE Statement  DELETE permanently removes records from a table.  DELETE can delete one or more records in a table.  Use the WHERE clause to DELETE only specific records. The SQL DELETE syntax The general syntax is: 1. DELETE table-name To delete specific records append a WHERE clause: 1. DELETE table-name WHERE condition SQL DELETE Examples Problem: Delete all products. 1. DELETE Product Problem: Delete products over $50. 1. DELETE Product WHERE UnitPrice > 50 Problem: Delete customer with Id = 21. 1. DELETE Customer WHERE Id = 21 This is a more common scenario in which a single record is deleted. SQL ORDER BY Clause  SELECT returns records in no particular order.  To ensure a specific order use the ORDER BY clause.  ORDER BY allows sorting by one or more columns.  Records can be returned in ascending or descending order. The SQL ORDER BY syntax The general syntax is: 1. SELECT column-names FROM table-name WHERE condition ORDER BY Column-names
  • 10. SQL ORDER BY Examples Problem: List all suppliers in alphabetical order 1. SELECT CompanyName, ContactName, City, Country FROM Supplier ORDER BY CompanyName The default sort order is ascending, that is, low-high or 1-100 Problem: List all suppliers in reverse alphabetical order 1. SELECT CompanyName, ContactName, City, Country FROM Supplier ORDER BY CompanyName DESC The keyword DESC denotes descending, i.e., reverse order 100 - 1. Problem: List all customers ordered by country, then by city within each country ordering by one or more columns is possible. 1. SELECT FirstName, LastName, City, Country FROM Customer ORDER BY Country, City Problem: List all suppliers in the USA, Japan, and Germany, ordered by city, then by company name in reverse order 1. SELECT Id, CompanyName, City, Country FROM Supplier WHERE Country IN ('USA', 'Japan', 'Germany') ORDER BY Country ASC, CompanyName DESC This shows that you can order by more than one column. ASC denotes ascending, but is optional as it is the default sort order. Problem: Show all orders, sorted by total amount, the largest first, within each year 1. SELECT Id, OrderDate, CustomerId, TotalAmount FROM [Order] ORDER BY YEAR(OrderDate) ASC, TotalAmount DESC Note: DESC means descending, but is optional as it is the default sort order. [Order] must be bracketed because it also is a key work in SQL. Notice the year breakpoints: 2012 - 2013 and 2013 - 2014. Each year starts with the highest TotalAmounts.
  • 11. This shows that other data types, such as numbers, dates, and bits can also be sorted. Note: YEAR is a built-in function which returns the year from a date. SQL SELECT TOP Statement  The SELECT TOP statement returns a specified number of records.  SELECT TOP is useful when working with very large datasets.  Non SQL Server databases use keywords like LIMIT, OFFSET, and ROWNUM. The SQL SELECT TOP syntax The general syntax is: 1. SELECT TOP n column-names FROM table-name SQL SELECT TOP Problem: List top 10 most expensive products 1. SELECT TOP 10 Id, ProductName, UnitPrice, Package FROM Product ORDER BY UnitPrice DESC SQL OFFSET-FETCH Clause  OFFSET excludes the first set of records.  OFFSET can only be used with an ORDER BY clause.  OFFSET with FETCH NEXT returns a defined window of records.  OFFSET with FETCH NEXT is great for building pagination support. The SQL ORDER BY OFFSET syntax The general syntax to exclude first n records is: 1. SELECT column-names FROM table-name ORDER BY column-names OFFSET n ROWS To exclude first n records and return only the next m records: 1. SELECT column-names FROM table-name ORDER BY column-names OFFSET n ROWS FETCH NEXT m ROWS ONLY This will return only record (n + 1) to (n + 1 + m). See example below.
  • 12. SQL OFFSET-FETCH Examples Problem: Get all but the 10 most expensive products sorted by price 1. SELECT Id, ProductName, UnitPrice, Package FROM Product ORDER BY UnitPrice DESC OFFSET 10 ROWS Problem: Get the 10th to 15th most expensive products sorted by price 1. SELECT Id, ProductName, UnitPrice, Package FROM Product ORDER BY UnitPrice DESC OFFSET 10 ROWS FETCH NEXT 5 ROWS ONLY SQL SELECT DISTINCT Statement  SELECT DISTINCT returns only distinct (different) values.  SELECT DISTINCT eliminates duplicate records from the results.  DISTINCT can be used with aggregates: COUNT, AVG, MAX, etc.  DISTINCT operates on a single column. DISTINCT for multiple columns is not supported. The SQL SELECT DISTINCT syntax The general syntax is: 1. SELECT DISTINCT column-name FROM table-name Can be used with COUNT and other aggregates 1. SELECT COUNT (DISTINCT column-name)FROM table-name SQL SELECT Examples Problem: List all supplier countries in alphabetical order. 1. SELECT DISTINCT Country FROM Supplier ORDER BY COUNTRY Problem: List the number of supplier countries 1. SELECT COUNT (DISTINCT Country) FROM Supplier
  • 13. SQL SELECT MIN, MAX Statement  SELECT MIN returns the minimum value for a column.  SELECT MAX returns the maximum value for a column. The SQL SELECT MIN and MAX syntax The general MIN syntax is: 1. SELECT MIN(column-name) FROM table-name The general MAX syntax is: 1. SELECT MAX(column-name) FROM table-name SQL SELECT MAX and MIN Examples Problem: Find the largest order placed in 2014 1. SELECT MAX(TotalAmount) FROM [Order] WHERE YEAR(OrderDate) = 2014 Problem: Find the last order date in 2013 1. SELECT MAX(OrderDate) FROM [Order] WHERE YEAR(OrderDate) = 2013 MIN and MAX can also be used with numeric and date types. SQL SELECT COUNT, SUM, AVG  SELECT COUNT returns a count of the number of data values.  SELECT SUM returns the sum of the data values.  SELECT AVG returns the average of the data values. The SQL SELECT COUNT, SUM, and AVG syntax The general COUNT syntax is: 1. SELECT COUNT(column-name) FROM table-name The general SUM syntax is: 1. SELECT SUM(column-name)FROM table-name The general AVG syntax is: 1. SELECT AVG(column-name)FROM table-name
  • 14. SQL SELECT COUNT, SUM, and AVG Examples Problem: Find the number of customers 1. SELECT COUNT(Id)FROM Customer Problem: Compute the total amount sold in 2013 1. SELECT SUM(TotalAmount) FROM [Order] WHERE YEAR(OrderDate) = 2013 Problem: Compute the average size of all orders 1. SELECT AVG(TotalAmount) FROM [Order] SQL WHERE AND, OR, NOT Clause  WHERE conditions can be combined with AND, OR, and NOT.  A WHERE clause with AND requires that two conditions are true.  A WHERE clause with OR requires that one of two conditions is true.  A WHERE clause with NOT negates the specified condition. The WHERE with AND, OR, NOT syntax A WHERE clause with AND: 1. SELECT column-names FROM table-name WHERE condition1 AND condition2 A WHERE clause with OR: 1. UPDATE table-name SET column-name = value WHERE condition1 OR condition2 A WHERE clause with NOT: 1. DELETE table-name WHERE NOT condition SQL WHERE with AND, OR, and NOT Examples Problem: Get customer named Thomas Hardy 1. SELECT Id, FirstName, LastName, City, Country FROM Customer WHERE FirstName = 'Thomas' AND LastName = 'Hardy'
  • 15. Problem: List all customers from Spain or France 1. SELECT Id, FirstName, LastName, City, Country FROM Customer WHERE Country = 'Spain' OR Country = 'France' Problem: List all customers that are not from the USA 1. SELECT Id, FirstName, LastName, City, Country FROM Customer WHERE NOT Country = 'USA' Problem: List all orders that not between $50 and $15000 1. SELECT Id, OrderDate, CustomerId, TotalAmount FROM [Order] WHERE NOT (TotalAmount >= 50 AND TotalAmount <= 15000) ORDER BY TotalAmount DESC SQL WHERE BETWEEN Clause  WHERE BETWEEN returns values that fall within a given range.  WHERE BETWEEN is a shorthand for >= AND <=.  BETWEEN operators is inclusive: begin and end values are included. The definitive guide for data professionals The SQL WHERE BETWEEN syntax The general syntax is: 1. SELECT column-names FROM table-name WHERE column-name BETWEEN value1 AND value2 SQL WHERE BETWEEN Examples Problem: List all products between $10 and $20 1. SELECT Id, ProductName, UnitPrice FROM Product WHERE UnitPrice BETWEEN 10 AND 20 ORDER BY UnitPrice Problem: List all products not between $10 and $100 sorted by price. 1. SELECT Id, ProductName, UnitPrice FROM Product WHERE UnitPrice NOT BETWEEN 5 AND 100 ORDER BY UnitPrice
  • 16. Problem: Get the number of orders and amount sold between Jan 1, 2013 and Jan 31, 2013. 1. SELECT COUNT(Id), SUM(TotalAmount)FROM [Order] WHERE OrderDate BETWEEN '1/1/2013' AND '1/31/2013' SQL WHERE IN Clause  WHERE IN returns values that matches values in a list or sub query.  WHERE IN is a shorthand for multiple OR conditions. The SQL WHERE IN syntax The general syntax is: 1. SELECT column-names FROM table-name WHERE column-name IN (values) SQL WHERE IN Examples Problem: List all suppliers from the USA, UK, OR Japan 1. SELECT Id, CompanyName, City, Country FROM Supplier WHERE Country IN ('USA', 'UK', and ‘Japan’) Problem: List all products that are not exactly $10, $20, $30, $40, or $50 1. SELECT Id, ProductName, UnitPrice FROM Product WHERE UnitPrice NOT IN (10, 20, 30, 40, 50) Problem: List all customers that are from the same countries as the suppliers. 1. SELECT Id, FirstName, LastName, Country FROM Customer WHERE Country IN (SELECT Country FROM Supplier)
  • 17. SQL WHERE LIKE Statement  WHERE LIKE determines if a character string matches a pattern.  Use WHERE LIKE when only a fragment of a text value is known.  WHERE LIKE supports two wildcard match options: % and _. The SQL WHERE LIKE syntax The general syntax is: 1. SELECT column-names FROM table-name WHERE column- name LIKE value Optional Wildcard characters allowed in 'value' are % (percent) and _ (underscore). A % matches any string with zero or more characters. An _ matches any single character. SQL WHERE LIKE Examples Problem: List all products with names that start with 'Ca' 1. SELECT Id, ProductName, UnitPrice, Package FROM Product WHERE ProductName LIKE 'Ca%' Problem: List all products that start with 'Cha' or 'Chan' and have one more character. 1. SELECT Id, ProductName, UnitPrice, Package FROM Product WHERE ProductName LIKE 'Cha_' OR ProductName LIKE 'Chan_' SQL IS NULL Clause  NULL is a special value that signifies 'no value'.  Comparing a column to NULL using the = operator is undefined.  Instead, use WHERE IS NULL or WHERE IS NOT NULL. The SQL WHERE IS NULL syntax
  • 18. The general syntax is: 1. SELECT column-names FROM table-name WHERE column-name IS NULL The general not null syntax is: 1. SELECT column-names FROM table-name WHERE column-name IS NOT NULL SQL WHERE IS NULL Examples Problem: List all suppliers that have no fax number 1. SELECT Id, CompanyName, Phone, Fax FROM Supplier WHERE Fax IS NULL Problem: List all suppliers that do have a fax number 1. SELECT Id, CompanyName, Phone, Fax FROM Supplier WHERE Fax IS NOT NULL SQL GROUP BY Clause  The GROUP BY clause groups records into summary rows.  GROUP BY returns one records for each group.  GROUP BY typically also involves aggregates: COUNT, MAX, SUM, AVG, etc.  GROUP BY can group by one or more columns. The SQL GROUP BY syntax The general syntax is: 1. SELECT column-names FROM table-name WHERE condition GROUP BY column-names The general syntax with ORDER BY is: 1. SELECT column-names FROM table-name WHERE condition GROUP BY column-names ORDER BY column-names
  • 19. SQL GROUP BY Examples Problem: List the number of customers in each country 1. SELECT COUNT(Id), Country FROM Customer GROUP BY Country Problem: List the number of customers in each country sorted high to low 1. SELECT COUNT(Id), Country FROM Customer GROUP BY Country ORDER BY COUNT(Id) DESC Problem: List the total amount ordered for each customer SELECT SUM(O.TotalPrice), C.FirstName, C.LastName FROM [Order] O JOIN Customer C ON O.CustomerId = C.Id GROUP BY C.FirstName, C.LastName ORDER BY SUM(O.TotalPrice) DESC This query uses a JOIN with Customer to obtain customer names SQL HAVING Clause  HAVING filters records that work on summarized GROUP BY results.  HAVING applies to summarized group records, whereas WHERE applies to individual records.  Only the groups that meet the HAVING criteria will be returned.  HAVING requires that a GROUP BY clause is present.  WHERE and HAVING can be in the same query. The SQL HAVING syntax The general syntax is: 1. SELECT column-names FROM table-name WHERE condition GROUP BY column-names HAVING condition The general syntax with ORDER BY is: 1. SELECT column-names FROM table-name WHERE condition GROUP BY column- names HAVING condition ORDER BY column-names
  • 20. SQL GROUP BY Examples Problem: List the number of customers in each country. Only include countries with more than 10 customers. 1. SELECT COUNT(Id), Country FROM Customer GROUP BY Country Problem: List the number of customers in each country, except the USA, sorted high to low. Only include countries with 9 or more customers. 1. SELECT COUNT(Id), Country FROM Customer WHERE Country <> 'USA' GROUP BY Country HAVING COUNT (Id) >= 9 ORDER BY COUNT(Id) DESC Problem: List all customer with average orders between $1000 and $1200. SELECT AVG(TotalAmount), FirstName, LastName FROM [Order] O JOIN Customer C ON O.CustomerId = C.Id GROUP BY FirstName, LastName HAVING AVG(TotalAmount) BETWEEN 1000 AND 1200 SQLAlias  An Alias is a shorthand for a table or column name.  Aliases reduce the amount of typing required to enter a query.  Complex queries with aliases are generally easier to read.  Aliases are useful with JOINs and aggregates: SUM, COUNT, etc.  An Alias only exists for the duration of the query. The SQL Alias syntax The general syntax is: 1. SELECT column-name AS alias-name FROM table-name alias-name WHERE condition
  • 21. SQL Alias Examples Problem: List total customers in each country. Display results with easy to understand column headers. 1. SELECT COUNT (C.Id) AS TotalCustomers, C.Country AS Nation FROM Customer C GROUP BY C.Country TotalCustomers and Nation are column aliases. The table alias (C) in this example is not particularly useful. Problem: List the total amount ordered by customer with easy to read column headers 1. SELECT C.Id AS Identifier, C.LastName + ', ' + C.FirstName AS CustomerName, SUM(O.TotalAmount) AS TotalSpent FROM [Order] O JOIN Customer C ON O.CustomerId = C.Id GROUP BY C.Id, C.LastName + ', ' + C.FirstName ORDER BY TotalSpent DESC The aliases significantly simplify writing the JOIN and ORDER BY clauses. The C alias in C.Id helps identify the Customer Id rather then the Order Id. SQL JOIN  A SQL JOIN combines records from two tables.  A JOIN locates related column values in the two tables.  A query can contain zero, one, or multiple JOIN operations.  INNER JOIN is the same as JOIN; the keyword INNER is optional. Different types of JOINs  (INNER) JOIN: Select records that have matching values in both tables.
  • 22.  LEFT (OUTER) JOIN: Select records from the first (left-most) table with matching right table records.  RIGHT (OUTER) JOIN: Select records from the second (right-most) table with matching left table records.  FULL (OUTER) JOIN: Selects all records that match either left or right table records. All INNER and OUTER keywords are optional. Details about the differences between these JOINs are available in subsequent tutorial pages. The SQL JOIN syntax The general syntax is: 1. SELECT column-names FROM table-name1 JOIN table-name2 ON column-name1 = column-name2 WHERE condition The general syntax with INNER is: 1. SELECT column-names FROM table-name1 INNER JOIN table-name2 ON column-name1 = column-name2 WHERE condition Note: The INNER keyword is optional: it is the default as well as the most common only used JOIN operation.
  • 23. SQL JOIN Examples Problem: List all orders with customer information 1. SELECT OrderNumber, TotalAmount, FirstName, LastName, City, Country FROM [Order] JOIN Customer ON [Order].CustomerId = Customer.Id In this example using table aliases for [Order] and Customer might have been useful. Problem: List all orders with product names, quantities, and prices 1. SELECT O.OrderNumber, CONVERT(date,O.OrderDate) AS Date, P.ProductName, I.Quantity, I.UnitPrice FROM [Order] O JOIN OrderItem I ON O.Id = I.OrderId JOIN Product P ON P.Id = I.ProductId ORDER BY O.OrderNumber This query performs two JOIN operations with 3 tables. The O, I, and P are table aliases. Date is a column alias. SQL LEFT JOIN  LEFT JOIN performs a join starting with the first (left-most) table and then any matching second (right-most) table records.  LEFT JOIN and LEFT OUTER JOIN are the same. The SQL LEFT JOIN syntax The general syntax is: 1. SELECT column-names FROM table-name1 LEFT JOIN table-name2 ON column-name1 = column-name2 WHERE condition
  • 24. SQL LEFT JOIN Example The general LEFT OUTER JOIN syntax is: SELECT OrderNumber, TotalAmount, FirstName, LastName, City, Country FROM Customer C LEFT JOIN [Order] O ON O.CustomerId = C.Id ORDER BY TotalAmount This will list all customers, whether they placed any order or not. The ORDER BY TotalAmount shows the customers without orders first (i.e.TotalMount is NULL). SQL RIGHT JOIN  RIGHT JOIN performs a join starting with the second (right-most) table and then any matching first (left-most) table records.  RIGHT JOIN and RIGHT OUTER JOIN are the same. The SQL RIGHT JOIN syntax The general syntax is: 1. SELECT column-names FROM table-name1 RIGHT JOIN table-name2 ON column-name1 = column-name2 WHERE condition The general RIGHT OUTER JOIN syntax is: 1. SELECT column-names FROM table-name1 RIGHT OUTER JOIN table- name2 ON column-name1 = column-name2 WHERE condition SQL RIGHT JOIN Example
  • 25. Problem: List customers that have not placed orders 1. SELECT TotalAmount, FirstName, LastName, City, Country FROM [Order] O RIGHT JOIN Customer C ON O.CustomerId = C.Id WHERE TotalAmount IS NULL This returns customers that, when joined, have no matching order. SQL FULL JOIN  FULL JOIN returns all matching records from both tables whether the other table matches or not.  FULL JOIN can potentially return very large datasets.  FULL JOIN and FULL OUTER JOIN are the same. The SQL FULL JOIN syntax The general syntax is: 1. SELECT column-names FROM table-name1 FULL JOIN table-name2 ON column-name1 = column-name2 WHERE condition The general FULL OUTER JOIN syntax is: 1. SELECT column-names FROM table-name1 FULL OUTER JOIN table- name2 ON column-name1 = column-name2 WHERE condition SQL FULL JOIN Examples Problem: Match all customers and suppliers by country 1. SELECT C.FirstName, C.LastName, C.Country AS CustomerCountry, S.Country AS SupplierCountry, S.CompanyName FROM Customer C FULL JOIN Supplier S ON C.Country = S.Country ORDER BY C.Country, S.Country
  • 26. This returns suppliers that have no customers in their country, and customers that have no suppliers in their country, and customers and suppliers that are from the same country. SQL SELF JOIN  A self JOIN occurs when a table takes a 'selfie'.  A self JOIN is a regular join but the table is joined with itself.  This can be useful when modeling hierarchies.  They are also useful for comparisons within a table The SQL Self JOIN syntax The general syntax is: 1. SELECT column-names FROM table-name T1 JOIN table-name T2 WHERE condition T1 and T2 are different table aliases for the same table SQL Self JOIN Examples Problem: Match customers that are from the same city and country 1. SELECT B.FirstName AS FirstName1, B.LastName AS LastName1, A.FirstName AS FirstName2, A.LastName AS LastName2, B.City, B.Country FROM Customer A, Customer B WHERE A.Id <> B.Id AND A.City = B.City AND A.Country = B.Country ORDER BY A.Country A and B are aliases for the same Customer table. SQL UNION Clause  UNION combines the result sets of two queries.  Column data types in the two queries must match.  UNION combines by column position rather than column name.
  • 27. The SQL UNION syntax The general syntax is: 1. SELECT column-names FROM table-name UNION SELECT column-names FROM table-name SQL UNION Examples Problem: List all contacts, i.e., suppliers and customers. 1. SELECT 'Customer' As Type, FirstName + ' ' + LastName AS ContactName, City, Country, Phone FROM Customer UNION SELECT 'Supplier', ContactName, City, Country, Phone FROM Supplier This is a simple example in which the table alias would be useful SQL Subqueries  A subquery is a SQL query within a query.  Subqueries are nested queries that provide data to the enclosing query.  Subqueries can return individual values or a list of records  Subqueries must be enclosed with parenthesis The SQL subquery syntax There is no general syntax; subqueries are regular queries placed inside parenthesis. Subqueries can be used in different ways and at different locations inside a query: Here is an subquery with the IN operator 1. SELECT column-names FROM table-name1 WHERE value IN (SELECT column-name FROM table-name2 WHERE condition) Subqueries can also assign column values for each record: 1. SELECT column1 = (SELECT column-name FROM table- name WHERE condition),column-names FROM table-name WEHRE condition
  • 28. SQL Subquery Examples Problem: List products with order quantities greater than 100. 1. SELECT ProductName FROM Product WHERE Id IN (SELECT ProductId FROM OrderItem WHERE Quantity > 100) SQL Subquery Examples Problem: List all customers with their total number of orders 1. SELECT FirstName, LastName,OrderCount = (SELECT COUNT(O.Id) FROM [Order] O WHERE O.CustomerId = C.Id)FROM Customer C This is a correlated subquery because the subquery references the enclosing query (i.e. the C.Id in the WHERE clause). SQL WHERE ANY, ALL Clause  ANY and ALL keywords are used with a WHERE or HAVING clause.  ANY and ALL operate on subqueries that return multiple values.  ANY returns true if any of the subquery values meet the condition.  ALL returns true if all of the subquery values meet the condition. The SQL WHERE ANY and ALL syntax The general ANY syntax is: 1. SELECT column-names FROM table-name WHERE column-name operator ANY (SELECT column-name FROM table-name WHERE condition) The general ALL syntax is: 1. SELECT column-names FROM table-name WHERE column-name operator ALL (SELECT column-name FROM table-name WHERE condition) SQL ANY Example Problem: Which products were sold by the unit (i.e. quantity = 1) 1. SELECT ProductName FROM Product WHERE Id = ANY (SELECT ProductId FROM OrderItem WHERE Quantity = 1)
  • 29. SQL ALL Example Problem: List customers who placed orders that are larger than the average of each customer order 1. SELECT DISTINCT FirstName + ' ' + LastName as CustomerName FROM Customer, [Order] WHERE Customer.Id = [Order].CustomerId AND TotalAmount > ALL (SELECT AVG(TotalAmount) FROM [Order] GROUP BY CustomerId) SQL WHERE EXISTS Statement  WHERE EXISTS tests for the existence of any records in a subquery.  EXISTS returns true if the subquery returns one or more records.  EXISTS is commonly used with correlated subqueries. The SQL EXISTS syntax The general syntax is: 1. SELECT column-names FROM table-name WHERE EXISTS (SELECT column- name FROM table-name WHERE condition) SQL EXISTS Example Problem: Find suppliers with products over $100. 1. SELECT CompanyName FROM Supplier WHERE EXISTS (SELECT ProductName FROM Product WHERE SupplierId = Supplier.Id AND UnitPrice > 100) This is a correlated subquery because the subquery references the enclosing query (with Supplier.Id). SQL SELECT INTO Statement  SELECT INTO copies data from one table into a new table.  SELECT INTO creates a new table located in the default file group. The SQL SELECT INTO syntax
  • 30. The general syntax is: 1. SELECT column-names INTO new-table-name FROM table-name WHERE EXISTS (SELECT column-name FROM table-name WHERE condition) The new table will have column names as specified in the query. SQL SELECT INTO Example Problem: Copy all suppliers from USA to a new SupplierUSA table. 1. SELECT * INTO SupplierUSA FROM Supplier WHERE Country = 'USA' SQL INSERT INTO SELECT Statement  INSERT INTO SELECT copies data from one table to another table.  INSERT INTO SELECT requires that data types in source and target tables match. The SQL INSERT INTO SELECT syntax The general syntax is: 1. INSERT INTO table-name (column-names) SELECT column-names FROM table-name WHERE condition SQL INSERT SELECT INTO Problem: Copy all Canadian suppliers into the Customer table INSERT INTO Customer (FirstName, LastName, City, Country, Phone) SELECT LEFT(ContactName, CHARINDEX(' ',ContactName) - 1) AS FirstName, SUBSTRING(ContactName, CHARINDEX(' ',ContactName) + 1, 100) AS LastName, City, Country, Phone FROM Supplier WHERE Country = 'Canada' LEFT, CHARINDEX, and SUBSTRING are built-in functions. These are the two new Customer records
  • 31. SQL Injection  SQL Injection is a code injection technique.  It is the placement of malicious code in SQL strings.  SQL Injection is one of the most common web hacking techniques.  These attacks only work with apps that internally use SQL. SQL Keywords  SQL Server uses reserved words for database operations.  Reserved keywords are part of the SQL Server T-SQL grammar.  SQL Server has claimed current and future reserved words.  Keywords can be used as identifiers by placing them between []. Current T-SQL Keywords ADD EXCEPT PERCENT ALL EXEC PLAN ALTER EXECUTE PRECISION AND EXISTS PRIMARY ANY EXIT PRINT AS FETCH PROC ASC FILE PROCEDURE AUTHORIZATION FILLFACTOR PUBLIC BACKUP FOR RAISERROR BEGIN FOREIGN READ BETWEEN FREETEXT READTEXT BREAK FREETEXTTABLE RECONFIGURE BROWSE FROM REFERENCES BULK FULL REPLICATION BY FUNCTION RESTORE CASCADE GOTO RESTRICT CASE GRANT RETURN CHECK GROUP REVOKE CHECKPOINT HAVING RIGHT CLOSE HOLDLOCK ROLLBACK CLUSTERED IDENTITY ROWCOUNT COALESCE IDENTITY_INSERT ROWGUIDCOL COLLATE IDENTITYCOL RULE
  • 32. COLUMN IF SAVE COMMIT IN SCHEMA COMPUTE INDEX SELECT CONSTRAINT INNER SESSION_USER CONTAINS INSERT SET CONTAINSTABLE INTERSECT SETUSER CONTINUE INTO SHUTDOWN CONVERT IS SOME CREATE JOIN STATISTICS CROSS KEY SYSTEM_USER CURRENT KILL TABLE CURRENT_DATE LEFT TEXTSIZE CURRENT_TIME LIKE THEN CURRENT_TIMESTAMP LINENO TO CURRENT_USER LOAD TOP CURSOR NATIONAL TRAN DATABASE NOCHECK TRANSACTION DBCC NONCLUSTERED TRIGGER DEALLOCATE NOT TRUNCATE DECLARE NULL TSEQUAL DEFAULT NULLIF UNION DELETE OF UNIQUE DENY OFF UPDATE DESC OFFSETS UPDATETEXT DISK ON USE DISTINCT OPEN USER DISTRIBUTED OPENDATASOURCE VALUES DOUBLE OPENQUERY VARYING DROP OPENROWSET VIEW DUMMY OPENXML WAITFOR DUMP OPTION WHEN ELSE OR WHERE END ORDER WHILE ERRLVL OUTER WITH
  • 33. ESCAPE OVER WRITETEXT Future T-SQL Keywords ABSOLUTE FOUND PRESERVE ACTION FREE PRIOR ADMIN GENERAL PRIVILEGES AFTER GET READS AGGREGATE GLOBAL REAL ALIAS GO RECURSIVE ALLOCATE GROUPING REF ARE HOST REFERENCING ARRAY HOUR RELATIVE ASSERTION IGNORE RESULT AT IMMEDIATE RETURNS BEFORE INDICATOR ROLE BINARY INITIALIZE ROLLUP BIT INITIALLY ROUTINE BLOB INOUT ROW BOOLEAN INPUT ROWS BOTH INT SAVEPOINT BREADTH INTEGER SCROLL CALL INTERVAL SCOPE CASCADED ISOLATION SEARCH CAST ITERATE SECOND CATALOG LANGUAGE SECTION CHAR LARGE SEQUENCE CHARACTER LAST SESSION CLASS LATERAL SETS CLOB LEADING SIZE COLLATION LESS SMALLINT COMPLETION LEVEL SPACE CONNECT LIMIT SPECIFIC CONNECTION LOCAL SPECIFICTYPE CONSTRAINTS LOCALTIME SQL
  • 34. CONSTRUCTOR LOCALTIMESTAMP SQLEXCEPTION CORRESPONDING LOCATOR SQLSTATE CUBE MAP SQLWARNING CURRENT_PATH MATCH START CURRENT_ROLE MINUTE STATE CYCLE MODIFIES STATEMENT DATA MODIFY STATIC DATE MODULE STRUCTURE DAY MONTH TEMPORARY DEC NAMES TERMINATE DECIMAL NATURAL THAN DEFERRABLE NCHAR TIME DEFERRED NCLOB TIMESTAMP DEPTH NEW TIMEZONE_HOUR DEREF NEXT TIMEZONE_MINUTE DESCRIBE NO TRAILING DESCRIPTOR NONE TRANSLATION DESTROY NUMERIC TREAT DESTRUCTOR OBJECT TRUE DETERMINISTIC OLD UNDER DICTIONARY ONLY UNKNOWN DIAGNOSTICS OPERATION UNNEST DISCONNECT ORDINALITY USAGE DOMAIN OUT USING DYNAMIC OUTPUT VALUE EACH PAD VARCHAR END-EXEC PARAMETER VARIABLE EQUALS PARAMETERS WHENEVER EVERY PARTIAL WITHOUT EXCEPTION PATH WORK EXTERNAL POSTFIX WRITE FALSE PREFIX YEAR FIRST PREORDER ZONE FLOAT PREPARE