0% found this document useful (0 votes)
1 views25 pages

Lesson_2_SQL_NoSQL

The document provides an overview of managing relational and non-relational data using Transact-SQL (T-SQL), covering key concepts such as removing duplicates, sorting, filtering results, and various types of joins. It explains the use of predicates, UNION, INTERSECT, and EXCEPT queries to manipulate and retrieve data from multiple tables. Additionally, it includes practical demonstrations and a summary of the topics discussed.

Uploaded by

oioioi1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views25 pages

Lesson_2_SQL_NoSQL

The document provides an overview of managing relational and non-relational data using Transact-SQL (T-SQL), covering key concepts such as removing duplicates, sorting, filtering results, and various types of joins. It explains the use of predicates, UNION, INTERSECT, and EXCEPT queries to manipulate and retrieve data from multiple tables. Additionally, it includes practical demonstrations and a summary of the topics discussed.

Uploaded by

oioioi1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Managing Relational and

Non-Relational Data

Transact-SQL - Querying Multiple Tables

Post-Graduation in Enterprise Data Science & Analytics


Agenda

• Transact-SQL

• Removing duplicates

• Sorting Results

• Filtering Results

• Using Predicates

• INNER Joins, OUTER Joins

• CROSS Joins and Self Joins

• UNION, INTERSECT and Except

2
T-SQL

• SELECT ALL Color


Blue
• Default behavior includes duplicates
Red
Yellow
SELECT Color Blue
FROM Production.Product; Yellow
Black

• SELECT DISTINCT

• Remove duplicates Color


Blue
SELECT DISTINCT Color Red
Yellow
FROM Production.Product;
Black

3
Sorting Results

• Use ORDER BY to sort results by one or more columns

• Aliases created in SELECT clause are visible to ORDER BY

• You can order by columns in the source that are not included in the SELECT
clause

• You can specify ASC or DESC (ASC is the default)

SELECT ProductSubcategoryID AS Category, Name


FROM Production.Product
ORDER BY Category, StandardCost DESC;

4
Limiting Sorted Results

• TOP allows you to limit the number or percentage of rows returned


by a query

• Works with ORDER BY clause to limit rows by sort order

• Added to SELECT clause:

• SELECT TOP (N) | TOP (N) Percent

• With percent, number of rows rounded up

• SELECT TOP (N) WITH TIES

• Retrieve duplicates where Applicable (nondeterministic)

SELECT TOP 10 Name, ListPrice


FROM Production.Product
ORDER BY ListPrice DESC;

5
Paging Through Results

OFFSET-FETCH is an extension to the ORDER BY clause:

• Allows filtering a requested range of rows

• Dependent on ORDER BY clause

• Provides a mechanism for paging through results

• Specify number of rows to skip, number of rows to retrieve:

ORDER BY <order_by_list>
OFFSET <offset_value> ROW(S)
FETCH FIRST|NEXT <fetch_value>
ROW(S) ONLY

6
Demo
Demo 1 – Remove duplicates and sorting results

7
Filtering and Using Predicates

• Specify predicates in the WHERE CLAUSE

Predicates and Operators Description


=<> Compares values for equality / non-equality
Determines whether a specified value matches any value in a
IN
subquery or a list
BETWEEN Specifies na inclusive range to test
Determines whether a specific character string matches a
LIKE
specified pattern, which can include wildcards
Combines two Boolean expressions and returns TRUE only when
AND
both are TRUE
Combines two Boolean expressions and returns TRUE if either is
OR
TRUE
NOT Reverses the result of a search condition

8
Demo
Demo 2 – Filtering and Using Predicates

9
Introduction to Joins

• Join Concepts

• Join Syntax

• Inner Joins

• Outer Joins

• Cross Joins

• Self Joins

10
Join Concepts

• Combine rows from multiple tables by specifying matching criteria

• Usually based on primary key – foreign key relationships

• For example, return rows that combine data from the Employee and
SalesOrder tables by matching the Employee.EmployeeID primary key to the
SalesOrder.EmployeeID foreign key

• Concept is the same as sets in a Venn Diagram

Sales order
that were
taken by
employees

Employee SalesOrder

11
Inner Joins

• Return only rows where a match is found in both input tables

• Match rows based on attributes supplied in predicate

• If join predicate operator is =, also known as equi-join

SELECT emp.FirstName, ord.Ammount


FROM HR.Employee AS emp
[INNER] JOIN Sales.SalesOrder AS ord
ON emp.EmployeeID = ord.EmployeeID

Set returned
by inner join

Employee SalesOrder

12
Demo
Demo 3 – Inner Joins

13
Outer Joins

• Return all rows from one table and any matching rows from
second table SELECT emp.FirstName, ord.Ammount
FROM HR.Employee AS emp
• One table’s rows are “preserved” LEFT [OUTER] JOIN Sales.SalesOrder AS ord
ON emp.EmployeeID = ord.EmployeeID
• Designated with LEFT, RIGHT, FULL keyword

• All rows from preserved table output to result set


Set returned by
left outer join
• Matches from other table retrieved

• Additional rows added to results for non-matched rows

• NULLs added in places where attributes do not match

• Example: Return all employees and for those who have


taken orders, return the order amount. Employees without
Employee SalesOrder
matching order will display NULL for order ammount

14
Demo
Demo 4 – Outer Joins

15
Cross Joins

• Combine each row from first table with each row from
second table Employee Product
EmployeeID FirstName ProductID Name
1 Dan 1 Widget
• All possible combinations output 2 Peter 2 Gizmo

• Logical Foundation for inner and outer joins SELECT emp.FirstName, prd.Name
FROM HR.Employee AS emp
• Inner joins start with Cartesian product adds filders CROSS JOIN Production.Product AS prd;

• Outer join takes Cartesian output, filtered, adds back non-matching


rows (with NULL placeholders)
Result
• Due to Cartesian product output, not typically a desired FirstName Name
Dan Widget
form of join Dan Gizmo
Peter Widget
• Some usefull exceptions
Peter Gizmo
• Table of numbers, generating data for testing

16
Self Joins

• Compare rows in same table to each Employee


EmployeeID FirstName Manager ID
other 1 Dan NULL
2 Aisha 1
3 Rosie 1
• Create two instances of same table in 4 Naomi 3

FROM clause
SELECT emp.FirstName AS Employee,
man.FirstName AS Manager
• At least one alias required
FROM HR.Employee AS emp
LEFT JOIN HR.Employee AS man
• Exampe: Return all employees and the ON emp.ManagerID = man.EmployeeID;

name of employee’s manager Result


Employee Manager
Dan NULL
Aisha Dan
Rosie Dan
Naomi Rosie

17
UNION

• UNION returns a result set of distinct rows combined


from all statements

• UNION removes duplicates during query processing


(affects performance)

• UNION ALL retains duplicates during query processing

-- only distinct rows from both queries are returned


SELECT countryregion, city FROM HR.Employees
UNION
SELECT countryregion, city FROM Sales.Customers

18
UNION Guidelines

• Column aliases

• Must be expressed in first query

• Number of columns

• Must be the same

• Data types

• Must be compatible for implicit conversion (or converted explicity)

19
INTERSECT Queries

• INTERSECT returns only distinct rows that appear in both


result sets

-- only rows that exist in both queries are returned


SELECT countryregion, city FROM HR.Employees
INTERSECT
SELECT countryregion, city FROM Sales.Customers

20
EXCEPT Queries

• EXCEPT returns only distinct rows that appear in the first set
but not the second

• Order in which sets are specified matters

-- only rows from Employees will be returned


SELECT countryregion, city FROM HR.Employees
EXCEPT
SELECT countryregion, city FROM Sales.Customers

21
Demo
Demo 5 – UNION, INTERSECT and EXCEPT queries

22
Summary

• Removing duplicates
• Sorting Results
• Filtering Results
• Using Predicates
• INNER Joins, OUTER Joins
• CROSS Joins and Self Joins
• UNION, INTERSECT and Except

23
Lab
Lab 2 – T-SQL Queries

24
Obrigado!

Morada: Campus de Campolide, 1070-312 Lisboa, Portugal


Tel: +351 213 828 610 | Fax: +351 213 828 611

You might also like