Querying Microsoft SQL
Server 2012
Exam 70-461
Combinando Tablas

Julián Castiblanco

Andrés Useche

http://julycastiblanco.blogspot.com/

usechejan@gmail.com

Julian_castiblancop@hotmail.com

Líder ITPros-DC

Líder ITPros-DC
•
•
•
•

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
•
•
•
•

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

Andrés
Useche
Agenda
•
•
•
•
•

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)
Certificaciones SQL Server 2012

http://www.microsoft.com/learning/en/us/mcsa-sql-certification.aspx
Certificaciones SQL Server 2012

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

http://www.microsoft.com/learning/en/us/mcse-sql-business-intelligence.aspx
Preséntalo Ahora!!!!

http://www.microsoft.com/learning/en-us/second-shot.aspx
http://www.microsoftvirtualacademy.com/trainingcourses/querying-microsoft-sql-server-2012-databasesjump-start#?fbid=wXtCFLgI5kM
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
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 as

synonyms, and joins (except, intersect); implement logic which uses dynamic SQL and system
metadata; write efficient, technically complex SQL queries, including all types of joins versus the
use 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 understand
different data access technologies; case versus isnull versus coalesce.
•

Implement sub-queries: Identify problematic elements in query plans; pivot and unpivot; apply operator; cte

statement; with statement
•

Implement data types: Use appropriate data; understand the uses and limitations of each data type; impact of
GUID (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 and
restrictions; implement XML schemas and handling of XML data; XML data: how to handle it in SQL Server and
when and when not to use it, including XML namespaces; import and export XML; XML indexing
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 other
programmatic objects; techniques for developing stored procedures; different types of
storeproc result; create stored procedure for data access layer; program stored
procedures, triggers, functions with T-SQL
Modify data by using INSERT, UPDATE, and DELETE statements: Given a set of code with
defaults, constraints, and triggers, determine the output of a set of DDL; know which
SQL statements are best to solve common requirements; use output statement
Combine datasets: Difference between UNION and UNION all; case versus isnull versus
coalesce; modify data by using MERGE statements
Work with functions: Understand deterministic, non-deterministic functions; scalar and
table values; apply built-in scalar functions; create and alter user-defined functions
(UDFs)
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 use
cursors; impact of scalar UDFs; combine multiple DML operations
Implement error handling:Implement try/catch/throw; use set based rather than row
based logic; transaction management
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)
Introducción a combinación de tablas

Cross Join
Inner Join

Outer Join

• Realiza un producto cartesiano
• También conocido como todos con todos

• 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

• 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

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
CROSS JOIN

ID NAME

AGE

Id

Fruta

Color

1

Ivan

17

1

Pera

Verde

2

Andrea

33

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
INNER JOIN

Id
ID STUDENT

1

Ivan
Andrea

3

Pipe

Cali

4

10

Tumaco

3

1

Pereira

2

2

2

1

IDCITY

CITY

Neiva

ID

STUDENT

IDCITY

Id

CITY

1

Ivan

2

2

Tumaco

2

Andrea

1

1

Pereira
LEFT OUTER JOIN

Id
ID STUDENT

1

Ivan
Andrea

3

Pipe

Cali

4

10

Tumaco

3

1

Pereira

2

2

2

1

IDCITY

CITY

Neiva

ID

STUDENT

IDCITY

Id

CITY

1

Ivan

2

2

Tumaco

2

Andrea

1

1

Pereira

3

Pipe

10

NULL

NULL
RIGHT OUTER JOIN

Id
ID STUDENT

1

Ivan
Andrea

3

Pipe

Tumaco

3

1

Pereira

2

2

2

1

IDCITY

CITY

Cali

10

ID

STUDENT

IDCITY

Id

CITY

1

Ivan

2

2

Tumaco

2

Andrea

1

1

Pereira

NULL

3

Cali

NULL NULL
SUBCONSULTAS

simpli
fican

Agrup
an

consul
tas

compl
ejas

SELECT
dbo.candidatos2014.Candidato,
dbo.candidatos2014.Corporación
FROM dbo.candidatos2014
WHERE idPartido = (SELECT TOP 1
idpartido FROM dbo.candidatos2014
GROUP BY idPartido ORDER BY
COUNT(*) DESC)
TABLAS DERIVADAS
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.

SELECT PA.Nombre
,NROCAN.NROCANDIDATOS
FROM dbo.Partidos AS PA
INNER JOIN (SELECT idpartido,
COUNT(*) AS NROCANDIDATOS FROM
dbo.candidatos2014
GROUP BY idPartido) AS NROCAN
ON PA.IDPartido=NROCAN.idpartido
ORDER BY NROCAN.NROCANDIDATOS DESC
COMMON TABLE EXPRESSION (CTE)

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.

WITH NROCAN AS (SELECT idpartido,
COUNT(*) AS NROCANDIDATOS
FROM dbo.candidatos2014 GROUP BY
idPartido)
SELECT PA.Nombre,
NROCAN.NROCANDIDATOS
FROM dbo.Partidos AS PA
INNER JOIN
NROCAN
ON PA.IDPartido=NROCAN.idpartido
ORDER BY NROCAN.NROCANDIDATOS DESC
APPLY
• A diferencia de los JOIN, en el cual el motor toma las 2
tablas y las cruza por uno o más campos indicados. El
comando APPLY puede generar una consulta en la segunda
tabla basada en cada una de las filas devultas por la tabla
que está a la derecha.
• La diferencia entre el CROSS APPLY y el OUTER APPLY es
que el primero devuelve solo los registros que encuentra en
ambas tablas y el OUTER devolverá NULLs en las columnas
donde no consiga un registro de salida en la tabla que se
encuentra a la derecha.
APPLY
SELECT D.deptid, D.deptname,
D.deptmgrid
,ST.empid, ST.empname,
ST.mgrid
FROM Departments AS D
CROSS APPLY
fn_getsubtree(D.deptmgrid) AS ST;
EL TALLER

http://www.slideshare.net/juliancastiblanco/t
aller-bsico-sentencias-sql
http://www.codeproject.com/KB/database/Visual_SQL_Joins/Visual_SQL_JOINS_orig.jpg
URL de Interés
• http://royal.pingdom.com/2008/04/08/the-history-ofcomputer-data-storage-in-pictures/
• http://rateyourmusic.com/list/jweber14/top_100_rock_ba
nds_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-461Microsoft/dp/0735666059/ref=sr_1_1?ie=UTF8&qid=1392
299933&sr=8-1&keywords=70-461
• https://www.facebook.com/groups/7399452387/

Introducción a JOINS, CTE, APPLY y SUBCONSULTAS

  • 1.
    Querying Microsoft SQL Server2012 Exam 70-461 Combinando Tablas Julián Castiblanco Andrés Useche http://julycastiblanco.blogspot.com/ usechejan@gmail.com Julian_castiblancop@hotmail.com Líder ITPros-DC Líder ITPros-DC
  • 2.
    • • • • 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 • • • • Ingeniero de Sistemas Especialista en Teleinformática MCP SQL SERVER 2012 Terpel como ingeniero de infraestructura IT - DBA Andrés Useche
  • 3.
    Agenda • • • • • Presentación de lascertificaciones 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)
  • 4.
    Certificaciones SQL Server2012 http://www.microsoft.com/learning/en/us/mcsa-sql-certification.aspx
  • 5.
    Certificaciones SQL Server2012 http://www.microsoft.com/learning/en/us/mcse-sql-data-platform.aspx
  • 6.
    Certificaciones SQL Server2012 http://www.microsoft.com/learning/en/us/mcse-sql-business-intelligence.aspx
  • 7.
  • 8.
  • 9.
    Contenido del examen70-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
  • 10.
    Contenido del examen70-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 as synonyms, and joins (except, intersect); implement logic which uses dynamic SQL and system metadata; write efficient, technically complex SQL queries, including all types of joins versus the use 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 understand different data access technologies; case versus isnull versus coalesce. • Implement sub-queries: Identify problematic elements in query plans; pivot and unpivot; apply operator; cte statement; with statement • Implement data types: Use appropriate data; understand the uses and limitations of each data type; impact of GUID (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 and restrictions; implement XML schemas and handling of XML data; XML data: how to handle it in SQL Server and when and when not to use it, including XML namespaces; import and export XML; XML indexing
  • 11.
    Contenido del examen70-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 other programmatic objects; techniques for developing stored procedures; different types of storeproc result; create stored procedure for data access layer; program stored procedures, triggers, functions with T-SQL Modify data by using INSERT, UPDATE, and DELETE statements: Given a set of code with defaults, constraints, and triggers, determine the output of a set of DDL; know which SQL statements are best to solve common requirements; use output statement Combine datasets: Difference between UNION and UNION all; case versus isnull versus coalesce; modify data by using MERGE statements Work with functions: Understand deterministic, non-deterministic functions; scalar and table values; apply built-in scalar functions; create and alter user-defined functions (UDFs)
  • 12.
    Contenido del examen70-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 use cursors; impact of scalar UDFs; combine multiple DML operations Implement error handling:Implement try/catch/throw; use set based rather than row based logic; transaction management
  • 13.
    IBM 305 RAMACcomputer en 1956. Tenía 50 discos de 24” con una capacidad de almacenamiento de 5 millones (poco menos de 5 MB)
  • 14.
    Introducción a combinaciónde tablas Cross Join Inner Join Outer Join • Realiza un producto cartesiano • También conocido como todos con todos • 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 • 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 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
  • 15.
  • 16.
  • 17.
    LEFT OUTER JOIN Id IDSTUDENT 1 Ivan Andrea 3 Pipe Cali 4 10 Tumaco 3 1 Pereira 2 2 2 1 IDCITY CITY Neiva ID STUDENT IDCITY Id CITY 1 Ivan 2 2 Tumaco 2 Andrea 1 1 Pereira 3 Pipe 10 NULL NULL
  • 18.
    RIGHT OUTER JOIN Id IDSTUDENT 1 Ivan Andrea 3 Pipe Tumaco 3 1 Pereira 2 2 2 1 IDCITY CITY Cali 10 ID STUDENT IDCITY Id CITY 1 Ivan 2 2 Tumaco 2 Andrea 1 1 Pereira NULL 3 Cali NULL NULL
  • 19.
  • 20.
    TABLAS DERIVADAS Basados enel 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. SELECT PA.Nombre ,NROCAN.NROCANDIDATOS FROM dbo.Partidos AS PA INNER JOIN (SELECT idpartido, COUNT(*) AS NROCANDIDATOS FROM dbo.candidatos2014 GROUP BY idPartido) AS NROCAN ON PA.IDPartido=NROCAN.idpartido ORDER BY NROCAN.NROCANDIDATOS DESC
  • 21.
    COMMON TABLE EXPRESSION(CTE) 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. WITH NROCAN AS (SELECT idpartido, COUNT(*) AS NROCANDIDATOS FROM dbo.candidatos2014 GROUP BY idPartido) SELECT PA.Nombre, NROCAN.NROCANDIDATOS FROM dbo.Partidos AS PA INNER JOIN NROCAN ON PA.IDPartido=NROCAN.idpartido ORDER BY NROCAN.NROCANDIDATOS DESC
  • 22.
    APPLY • A diferenciade los JOIN, en el cual el motor toma las 2 tablas y las cruza por uno o más campos indicados. El comando APPLY puede generar una consulta en la segunda tabla basada en cada una de las filas devultas por la tabla que está a la derecha. • La diferencia entre el CROSS APPLY y el OUTER APPLY es que el primero devuelve solo los registros que encuentra en ambas tablas y el OUTER devolverá NULLs en las columnas donde no consiga un registro de salida en la tabla que se encuentra a la derecha.
  • 23.
    APPLY SELECT D.deptid, D.deptname, D.deptmgrid ,ST.empid,ST.empname, ST.mgrid FROM Departments AS D CROSS APPLY fn_getsubtree(D.deptmgrid) AS ST;
  • 24.
  • 25.
  • 26.
    URL de Interés •http://royal.pingdom.com/2008/04/08/the-history-ofcomputer-data-storage-in-pictures/ • http://rateyourmusic.com/list/jweber14/top_100_rock_ba nds_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-461Microsoft/dp/0735666059/ref=sr_1_1?ie=UTF8&qid=1392 299933&sr=8-1&keywords=70-461 • https://www.facebook.com/groups/7399452387/