Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

26
Julián Castiblanco http://julycastiblanco.blogspot.com/ [email protected] Líder ITPros-DC Querying Microsoft SQL Server 2012 Exam 70-461 Combinando Tablas Andrés Useche [email protected] Líder ITPros-DC

Transcript of Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

Page 1: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

Julián Castiblancohttp://julycastiblanco.blogspot.com/

[email protected]

Líder ITPros-DC

Querying Microsoft SQL Server 2012Exam 70-461Combinando Tablas

Andrés [email protected]

Líder ITPros-DC

Page 2: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

• Ingeniero de Diseño & Automatización Electrónica• Especialista en Gerencia y Tecnologías de Información• MCT-MCSA-MCITP-MCTS en SQL SERVER• Synergy TPC SAS como consultor especializado en

bases de datos SQL Server

Julián

Castiblanco

Andrés

Useche

• Ingeniero de Sistemas• Especialista en Teleinformática• MCP SQL SERVER 2012• Terpel como ingeniero de infraestructura IT - DBA

Page 3: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

• Presentación de las certificaciones de SQL Server 2012.• Carreras del MVA• Contenido del examen 70-461• Introducción a combinación de tablas• Subconsultas y Expresiones de tabla comunes (CTE)

Agenda

Page 4: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

http://www.microsoft.com/learning/en/us/mcsa-sql-certification.aspx

Certificaciones SQL Server 2012

Page 5: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

http://www.microsoft.com/learning/en/us/mcse-sql-data-platform.aspx

Certificaciones SQL Server 2012

Page 6: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

http://www.microsoft.com/learning/en/us/mcse-sql-business-intelligence.aspx

Certificaciones SQL Server 2012

Page 7: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

http://www.microsoft.com/learning/en-us/second-shot.aspx

Preséntalo Ahora!!!!

Page 8: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

http://www.microsoftvirtualacademy.com/training-courses/querying-microsoft-sql-server-2012-databases-jump-start#?fbid=wXtCFLgI5kM

Page 9: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

Contenido del examen 70-461

Create database objects (24%)• Create and alter tables using T-SQL syntax (simple statements): Create tables without using the built

in tools; ALTER; DROP; ALTER COLUMN; CREATE

• Create and alter views (simple statements): Create indexed views; create views without using the built in tools; CREATE, ALTER, DROP

• Design views : Ensure code non regression by keeping consistent signature for procedure, views and function (interfaces); security implications

• Create and modify constraints (simple statements) : Create constraints on tables; define constraints; unique constraints; default constraints; primary and foreign key constraints

• Create and alter DML triggers: Inserted and deleted tables; nested triggers; types of triggers; update functions; handle multiple rows in a session; performance implications of triggers

Page 10: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

Contenido del examen 70-461

Work with data (27%)• Query data by using SELECT statements: Use the ranking function to select top(X) rows for multiple categories in a

single query; write and perform queries efficiently using the new (SQL 2005/8->) code items such assynonyms, and joins (except, intersect); implement logic which uses dynamic SQL and systemmetadata; write efficient, technically complex SQL queries, including all types of joins versus theuse of derived tables; determine what code may or may not execute based on the tables provided;given a table with constraints, determine which statement set would load a table; use and understanddifferent data access technologies; case versus isnull versus coalesce.

• Implement sub-queries: Identify problematic elements in query plans; pivot and unpivot; apply operator; ctestatement; with statement

• Implement data types: Use appropriate data; understand the uses and limitations of each data type; impact ofGUID (newid, newsequentialid) on database performance, when to use what data type for columns

• Implement aggregate queries: New analytic functions; grouping sets; spatial aggregates; apply ranking functions

• Query and manage XML data: Understand XML datatypes and their schemas and interop w/, limitations andrestrictions; implement XML schemas and handling of XML data; XML data: how to handle it in SQL Server andwhen and when not to use it, including XML namespaces; import and export XML; XML indexing

Page 11: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

Contenido del examen 70-461

Modify data (24%)• Create and alter stored procedures (simple statements): Write a stored procedure to

meet a given set of requirements; branching logic; create stored procedures and otherprogrammatic objects; techniques for developing stored procedures; different types ofstoreproc result; create stored procedure for data access layer; program storedprocedures, triggers, functions with T-SQL

• Modify data by using INSERT, UPDATE, and DELETE statements: Given a set of code withdefaults, constraints, and triggers, determine the output of a set of DDL; know whichSQL statements are best to solve common requirements; use output statement

• Combine datasets: Difference between UNION and UNION all; case versus isnull versuscoalesce; modify data by using MERGE statements

• Work with functions: Understand deterministic, non-deterministic functions; scalar andtable values; apply built-in scalar functions; create and alter user-defined functions(UDFs)

Page 12: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

Contenido del examen 70-461

Troubleshoot and optimize (25%)

• Optimize queries : Understand statistics; read query plans; plan guides; DMVs; hints;statistics IO; dynamic vs. parameterized queries; describe the different join types(HASH, MERGE, LOOP) and describe the scenarios they would be used in

• Manage transactions: Mark a transaction; understand begin tran, commit, and rollback;implicit vs explicit transactions; isolation levels; scope and type of locks; trancount

• Evaluate the use of row-based operations vs. set-based operations: When to usecursors; impact of scalar UDFs; combine multiple DML operations

• Implement error handling:Implement try/catch/throw; use set based rather than rowbased logic; transaction management

Page 13: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

IBM 305 RAMAC computer en 1956. Tenía 50 discos de 24” con una capacidad de almacenamiento de 5 millones (poco menos de 5 MB)

Page 14: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

• Realiza un producto cartesiano

• También conocido como todos con todos

Cross Join

• Combina las filas basado en una o más columnas comunes

• Normalmente las llaves primarias y las foráneas

• Solo muestra los registros que tengan un valor común en ambas tablas

Inner Join

• Preserva una de las tablas y en los registros que tengan un campo en común con la segunda tabla extrae la información que necesitamos, de lo contrario estas columnas quedarán con un valor no determinado (NULL)

• Puede ser LEFT Outer JOIN o RIGHT Outer JOIN

Outer Join

Introducción a combinación de tablas

Cuando en la consulta intervienen más de dos tablas el sistema va creando una tabla virtual con el resultado de la primera combinación y utiliza este para hacer el “join” con la siguiente tabla

Page 15: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

CROSS JOIN

ID NAME AGE

1 Ivan 17

2 Andrea 33

Id Fruta Color

1 Pera Verde

2 Mora Rojo

ID NAME AGE Id Fruta Color

1 Ivan 17 1 Pera Verde

1 Ivan 17 2 Mora Rojo

2 Andrea 33 1 Pera Verde

2 Andrea 33 2 Mora Rojo

Page 16: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

INNER JOIN

ID STUDENT IDCITY

1 Ivan 2

2 Andrea 1

3 Pipe 10

Id CITY

1 Pereira

2 Tumaco

3 Cali

4 Neiva

ID STUDENT IDCITY Id CITY

1 Ivan 2 2 Tumaco

2 Andrea 1 1 Pereira

Page 17: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

LEFT OUTER JOIN

ID STUDENT IDCITY

1 Ivan 2

2 Andrea 1

3 Pipe 10

Id CITY

1 Pereira

2 Tumaco

3 Cali

4 Neiva

ID STUDENT IDCITY Id CITY

1 Ivan 2 2 Tumaco

2 Andrea 1 1 Pereira

3 Pipe 10 NULL NULL

Page 18: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

RIGHT OUTER JOIN

ID STUDENT IDCITY

1 Ivan 2

2 Andrea 1

3 Pipe 10

Id CITY

1 Pereira

2 Tumaco

3 Cali

ID STUDENT IDCITY Id CITY

1 Ivan 2 2 Tumaco

2 Andrea 1 1 Pereira

NULL NULL NULL 3 Cali

Page 19: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

SUBCONSULTAS

simplifican

Agrupan

consultas

complejas

SELECTdbo.candidatos2014.Candidato,dbo.candidatos2014.CorporaciónFROM dbo.candidatos2014WHERE idPartido = (SELECT TOP 1 idpartido FROM dbo.candidatos2014GROUP BY idPartido ORDER BYCOUNT(*) DESC)

Page 20: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

TABLAS DERIVADAS

SELECT PA.Nombre,NROCAN.NROCANDIDATOS

FROM dbo.Partidos AS PAINNER JOIN (SELECT idpartido,

COUNT(*) AS NROCANDIDATOS FROMdbo.candidatos2014GROUP BY idPartido) AS NROCAN

ON PA.IDPartido=NROCAN.idpartidoORDER BY NROCAN.NROCANDIDATOS DESC

Basados en el resultado de una consulta se genera un conjunto de datos que será tratado como insumo que será tratado como una tabla para una consulta superior.

Page 21: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

COMMON TABLE EXPRESSION (CTE)

WITH NROCAN AS (SELECT idpartido,COUNT(*) AS NROCANDIDATOSFROM dbo.candidatos2014 GROUP BYidPartido)

SELECT PA.Nombre,NROCAN.NROCANDIDATOSFROM dbo.Partidos AS PAINNER JOIN NROCANON PA.IDPartido=NROCAN.idpartidoORDER BY NROCAN.NROCANDIDATOS DESC

Son subconsultas que hacen que el código se vea más limpio, haciendo más fácil su mantenimiento. Normalmente son utilizadas en consultar recursivas.

Page 22: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

APPLY

• A diferencia de los JOIN, en el cual el motor toma las 2tablas y las cruza por uno o más campos indicados. Elcomando APPLY puede generar una consulta en la segundatabla basada en cada una de las filas devultas por la tablaque está a la derecha.

• La diferencia entre el CROSS APPLY y el OUTER APPLY esque el primero devuelve solo los registros que encuentra enambas tablas y el OUTER devolverá NULLs en las columnasdonde no consiga un registro de salida en la tabla que seencuentra a la derecha.

Page 23: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

APPLY

SELECT D.deptid, D.deptname,D.deptmgrid

,ST.empid, ST.empname,ST.mgridFROM Departments AS D

CROSS APPLYfn_getsubtree(D.deptmgrid) AS ST;

Page 24: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

EL TALLER

http://www.slideshare.net/juliancastiblanco/taller-bsico-sentencias-sql

Page 25: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

http://www.codeproject.com/KB/database/Visual_SQL_Joins/Visual_SQL_JOINS_orig.jpg

Page 26: Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

URL de Interés

• http://royal.pingdom.com/2008/04/08/the-history-of-computer-data-storage-in-pictures/

• http://rateyourmusic.com/list/jweber14/top_100_rock_bands_of_the_70s/

• http://en.wikipedia.org/wiki/Latin_American_debt_crisis• http://www.registraduria.gov.co/?page=candidatos_2014• http://es.wikipedia.org/wiki/Anexo:Partidos_pol%C3%ADtic

os_de_Colombia• http://www.amazon.com/Training-Kit-Exam-70-461-

Microsoft/dp/0735666059/ref=sr_1_1?ie=UTF8&qid=1392299933&sr=8-1&keywords=70-461

• https://www.facebook.com/groups/7399452387/