Lesson_2_SQL_NoSQL
Lesson_2_SQL_NoSQL
Non-Relational Data
• Transact-SQL
• Removing duplicates
• Sorting Results
• Filtering Results
• Using Predicates
2
T-SQL
• SELECT DISTINCT
3
Sorting Results
• You can order by columns in the source that are not included in the SELECT
clause
4
Limiting Sorted Results
5
Paging Through Results
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
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
• 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
Sales order
that were
taken by
employees
Employee SalesOrder
11
Inner Joins
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
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;
16
Self Joins
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;
17
UNION
18
UNION Guidelines
• Column aliases
• Number of columns
• Data types
19
INTERSECT Queries
20
EXCEPT Queries
• EXCEPT returns only distinct rows that appear in the first set
but not the second
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!