A free training provided by Steve Stedman and Aaron Buma at Emergency Reporting to prepare for the Microsoft 70-461 SQL Queries exam. This session covers Set Operators, Derived Tables and Common Table Expressions (CTE’s). This is provided free of charge to give back to the SQL community.
SQL Server TOP(), Ranking, NTILE, and Aggregate FunctionsSteve Stedman
TOP(), Ranking, NTILE, and Aggregate Functions.
TOP(N)
RANK and DENSE_RANK
ROW_NUMBER
NTILE
OVER clause enhancements
LAG and LEAD, FIRST_VALUE and LAST_VALUE
PERCENT_RANK
PERCENTILE_DISC and PERCENTILE_CONT
CUME_DIST - Cumulative Distribution
More details:
http://stevestedman.com/2015/02/top-ranking-ntile-and-aggregate-functions/
The Date and Time functions section will include GETDATE(), DATEPART(), DATEADD(), DATEDIFF(), EOMONTH (2012), along with a variety of DATE/TIME FROMPARTS Functions. Following that will be the logical functions which includes CASE, IIF, CHOOSE, and COALESCE. ISNULL is usually covered in this section, but we already covered that in an earlier session.
This document discusses sorting algorithms. It begins by defining sorting as arranging items in a sequence. It notes that 25-50% of computing power is used for sorting activities. Common sorting applications include organizing lists of student data, test scores, and race results. Sorting methods described include selection sort, bubble sort, shell sort, and quick sort. Selection sort works by repeatedly finding the largest element and swapping it into the sorted portion of the array. Bubble sort compares adjacent elements and swaps them if out of order, pushing larger elements towards the end over multiple passes. Pseudocode and C++ code examples are provided to demonstrate how selection and bubble sort algorithms work on integer and string arrays.
This document discusses function parameters and argument passing in Python. It explains that parameters exist only within the function they are defined in, and values are assigned when calling the function. It demonstrates positional, keyword, and mixed argument passing, and shows how default values can be set for parameters. Functions can be called by passing arguments in different orders or specifying keywords. Key points are that parameters transfer information to functions, and various argument passing techniques exist.
The document discusses dynamic data structures in C including linked lists, stacks, queues, and dynamically linked lists. Linked lists store structures containing a data field and a pointer to the next structure. Stacks follow LIFO order using push and pop operations, while queues follow FIFO order using enqueue and dequeue operations. Dynamically linked lists allow inserting and deleting structures anywhere in the list using operations that update internal pointers. Memory for these dynamic structures is allocated using functions like malloc() and free(). Common errors involve failure to check for memory allocation errors or correctly update pointers when adding or removing structures.
The document discusses different algorithms for searching and sorting arrays, including sequential search, binary search, selection sort, and bubble sort. It provides pseudocode examples and step-by-step explanations of how each algorithm works. Sequential search sequentially checks each element to find a match. Binary search repeatedly halves the search space. Selection sort finds the maximum element and swaps it into sorted position. Bubble sort repeatedly compares and swaps adjacent elements.
SQL Server TOP(), Ranking, NTILE, and Aggregate FunctionsSteve Stedman
TOP(), Ranking, NTILE, and Aggregate Functions.
TOP(N)
RANK and DENSE_RANK
ROW_NUMBER
NTILE
OVER clause enhancements
LAG and LEAD, FIRST_VALUE and LAST_VALUE
PERCENT_RANK
PERCENTILE_DISC and PERCENTILE_CONT
CUME_DIST - Cumulative Distribution
More details:
http://stevestedman.com/2015/02/top-ranking-ntile-and-aggregate-functions/
The Date and Time functions section will include GETDATE(), DATEPART(), DATEADD(), DATEDIFF(), EOMONTH (2012), along with a variety of DATE/TIME FROMPARTS Functions. Following that will be the logical functions which includes CASE, IIF, CHOOSE, and COALESCE. ISNULL is usually covered in this section, but we already covered that in an earlier session.
This document discusses sorting algorithms. It begins by defining sorting as arranging items in a sequence. It notes that 25-50% of computing power is used for sorting activities. Common sorting applications include organizing lists of student data, test scores, and race results. Sorting methods described include selection sort, bubble sort, shell sort, and quick sort. Selection sort works by repeatedly finding the largest element and swapping it into the sorted portion of the array. Bubble sort compares adjacent elements and swaps them if out of order, pushing larger elements towards the end over multiple passes. Pseudocode and C++ code examples are provided to demonstrate how selection and bubble sort algorithms work on integer and string arrays.
This document discusses function parameters and argument passing in Python. It explains that parameters exist only within the function they are defined in, and values are assigned when calling the function. It demonstrates positional, keyword, and mixed argument passing, and shows how default values can be set for parameters. Functions can be called by passing arguments in different orders or specifying keywords. Key points are that parameters transfer information to functions, and various argument passing techniques exist.
The document discusses dynamic data structures in C including linked lists, stacks, queues, and dynamically linked lists. Linked lists store structures containing a data field and a pointer to the next structure. Stacks follow LIFO order using push and pop operations, while queues follow FIFO order using enqueue and dequeue operations. Dynamically linked lists allow inserting and deleting structures anywhere in the list using operations that update internal pointers. Memory for these dynamic structures is allocated using functions like malloc() and free(). Common errors involve failure to check for memory allocation errors or correctly update pointers when adding or removing structures.
The document discusses different algorithms for searching and sorting arrays, including sequential search, binary search, selection sort, and bubble sort. It provides pseudocode examples and step-by-step explanations of how each algorithm works. Sequential search sequentially checks each element to find a match. Binary search repeatedly halves the search space. Selection sort finds the maximum element and swaps it into sorted position. Bubble sort repeatedly compares and swaps adjacent elements.
Here are the key points about .NET:
- .NET is a software development platform from Microsoft that runs primarily on Windows. It introduces a new virtual machine called the Common Language Runtime (CLR) which compiles code into an intermediate language (IL) that can be executed on any operating system that supports .NET.
- Major languages supported include C#, Visual Basic .NET, and C++/CLI. These compile to IL rather than native machine code.
- The .NET Framework provides a large class library called Framework Class Library (FCL) which includes functionality for common tasks like database access, XML, networking, graphics etc.
- Major versions include 1.0 (released 2002), 1.1 (
SQL is a standard language for accessing and manipulating databases. It allows users to query, insert, update, and delete data. The document discusses SQL statements like SELECT, INSERT, UPDATE, DELETE and functions like JOIN, aggregate functions, and scalar functions. It provides examples of creating tables and manipulating data using DDL, DML, and DCL statements. Joins allow combining data from multiple tables based on common fields.
Oracle Database Administration I (1Z0-082) Exam Dumps 2024.pdfSkillCertProExams
• For a full set of 420+ questions. Go to
https://skillcertpro.com/product/oracle-database-administration-i-1z0-082-exam-questions/
• SkillCertPro offers detailed explanations to each question which helps to understand the concepts better.
• It is recommended to score above 85% in SkillCertPro exams before attempting a real exam.
• SkillCertPro updates exam questions every 2 weeks.
• You will get life time access and life time free updates
• SkillCertPro assures 100% pass guarantee in first attempt.
The document discusses various SQL commands and techniques. It provides explanations and examples of:
1) How to use the SPOOL command to output a SQL query to a text file. The SPOOL command directs query output to a file, and SPOOL OFF closes the file.
2) Common questions about SQL, including the differences between DDL, DML, and DCL commands, escaping special characters in queries, eliminating duplicate rows, generating primary keys, calculating time differences between dates, and adding to date values.
3) Techniques for counting distinct values or value ranges in a column, retrieving a specific row number from a table, and implementing IF-THEN-ELSE logic in a SQL
This document provides information about SQL queries using DML statements like INSERT, SELECT, UPDATE, DELETE. It includes examples of inserting data into a table using INSERT, selecting data from a table using SELECT, and selecting specific records using a WHERE clause. It also discusses using LIKE in the WHERE clause to filter results containing a substring. The objectives are to study SQL DML statements and design at least 10 queries using DML statements, operators, functions and set operators.
This document discusses common table expressions (CTEs) in MySQL 8.0. It begins with an introduction to CTEs, explaining how they provide an alternative to derived tables. The document then covers non-recursive and recursive CTEs. For non-recursive CTEs, it provides examples of finding the best and worst month of sales. For recursive CTEs, it demonstrates examples such as generating a sequence of numbers and traversing a employee hierarchy. The key benefits of CTEs over derived tables are also summarized, such as improved readability, ability to reference a CTE multiple times, and potential performance improvements from avoiding multiple materializations.
Charles WilliamsCS362Unit 3 Discussion BoardStructured Query Langu.docxchristinemaritza
Charles WilliamsCS362Unit 3 Discussion Board
Structured Query Language for Data Management 1
Structured Query Language for Data Management 36-04-17
Table of Contents
Phase 1- Database Design and DDL 3
Business Rules & Entity Tables 3
Entity Tables: 4
SQL CODE: 4
Screenshots: 8
Phase 2 – Security and DML 13
Task 1 14
Task 2 15
Task 3 16
Task 4 17
Task 5 18
Phase 3 - DML (Select) and Procedures 19
Task 1 19
Task 2 20
Task 3 21
Task 4 22
Task 5 23
Phase 4 – Architecture, Indexes 27
Step 1: CREATE TABLE [Degrees] 27
Step 2: Re-create ‘Classes’ TABLE to add ‘DegreeID’ column and INSERT 6 classes 29
Step 3: ALTER TABLE [Students] 31
Step 5: DML script to INSERT INTO the ‘Students’ table ‘DegreeID’ data 33
Step 6: Display ERD 36
Phase 5 – Views, Transactions, Testing and Performance 37
References 38
Phase 1- Database Design and DDL
I contracted to design and develop a database for CTU that will store individual and confidential university data. This database is required to give the back-end engineering to a front-end web application with an instinctive User/Interface (U/I) to be utilized by the college HR office. We've chosen to utilize Microsoft SQL Server 2012 given the way of information to be put away because it will be more secure, and it additionally gives a suite of server upkeep apparatuses to be deserted with the IT Department once the database and web application have been tried and acknowledged by college partners.
Amid our preparatory gatherings, CTU's necessities were characterized and enough perused to start making of the database. The accompanying areas contain the business tenets and element tables created amid the preparatory gatherings, and additionally duplicates of all the SQL code used to manufacture the database and make the Entity Relationship Diagram (ERD).
Business Rules & Entity Tables
Business Rules:
· A student has a name, a birth date, and gender.
· You must track the date the student started at the university and his or her current GPA, as well as be able to inactivate him or her without deleting information.
· For advising purposes, store the student's background/bio information. This is like a little story.
· An advisor has a name and an e-mail address.
· Students are assigned to one advisor, but one advisor may service multiple students.
· A class has a class code, name, and description.
· You need to indicate the specific classes a student is taking/has taken at the university. Track the date the student started a specific class and the grade earned in that class.
· Each class that a student takes has 4 assignments. Each assignment is worth 100 points.Entity Tables:
SQL CODE:
Create Database:
CREATE DATABASE [Cameron_CTU]
CONTAINMENT = NONE
ON PRIMARY
( NAME = N'Cameron_CTU', FILENAME = N'c:\Program Files\Microsoft SQL Server\MSSQL11.SCAMERON_CTU\MSSQL\DATA\Cameron_CTU.mdf' , SIZE = 3072KB , FILEGROWTH = 1024KB )
LOG ON
( NAME = N'Cameron_CTU_log', FILENAME = N'c:\Progra ...
This document discusses common table expressions (CTEs) in MySQL 8.0. It begins with an introduction to CTEs, explaining that they allow for subqueries to be defined before the main query similar to derived tables but with better performance and readability. It then provides examples of non-recursive and recursive CTEs. For non-recursive CTEs, it demonstrates finding the best and worst month of sales. For recursive CTEs, it shows examples of generating a sequence of numbers from 1 to 10 and generating missing dates in a date sequence. The document emphasizes that CTEs only need to be materialized once, improving performance over derived tables.
This document discusses new features in SQL Server including MERGE statements, table valued parameters, grouping sets, and FILESTREAM storage. MERGE statements allow inserting, updating, and deleting data in one statement based on matching or non-matching rows between two tables. Table valued parameters allow passing tables of data as parameters to stored procedures. Grouping sets enable grouping data by multiple columns in a single query. FILESTREAM storage integrates the database engine with the file system to allow storing large binary objects on disk for improved performance.
This document provides an overview of queries in Microsoft Access, including:
- Simple queries allow selecting records from one or more tables using criteria. Calculated fields can be created using the Expression Builder.
- More complex queries include grouping data, creating tables from queries, updating data, adding new records, and deleting records. Crosstab queries summarize and reformat data.
- The module teaches the concepts of queries, building queries visually, writing selection criteria, and using calculated fields and expressions. However, it does not cover everything about queries.
The document provides an introduction to the SQL language, including its main components of DML (Data Manipulation Language) and DDL (Data Definition Language). It discusses SQL concepts such as creating tables with data types, defining primary and foreign keys, and using basic queries with SELECT, FROM, WHERE and ORDER BY clauses.
The document discusses how to tune a query for better performance. It begins by explaining that the algorithm and approach are most important for performance and scalability. Writing procedural code should be avoided when possible in favor of set-based operations using SQL. Examples are provided of poorly written procedural code that could be improved by using SQL constructs instead. The document then demonstrates how to tune a sample query by adding relevant indexes and constraints based on the schema. Overall, the key points are to think in sets rather than procedurally, leverage SQL over procedural code, and understand how the schema and metadata impact query optimization.
Structured Query Language for Data Management 2 Sructu.docxjohniemcm5zt
Structured Query Language for Data Management 2
Sructured Query Language for Data Management 6
Table of Contents
Phase 1- Database Design and DDL 3
Business Rules & Entity Tables 3
Entity Tables: 4
SQL CODE: 4
Screenshots: 8
Phase 2 – Security and DML 13
Task 1 14
Task 2 15
Task 3 16
Task 4 17
Task 5 18
Phase 3 - DML (Select) and Procedures 19
Task 1 19
Task 2 20
Task 3 21
Task 4 22
Task 5 23
Phase 4 – Architecture, Indexes 27
Step 1: CREATE TABLE [Degrees] 27
Step 2: Re-create ‘Classes’ TABLE to add ‘DegreeID’ column and INSERT 6 classes 29
Step 3: ALTER TABLE [Students] 31
Step 5: DML script to INSERT INTO the ‘Students’ table ‘DegreeID’ data 33
Step 6: Display ERD 36
Phase 5 – Views, Transactions, Testing and Performance 37
References 38
Phase 1- Database Design and DDL
My team was recently contracted to design and develop a database for CTU that will store personal and confidential university data. This database is expected to provide the back-end architecture for a front-end web application with an intuitive User/Interface (U/I) to be used by the university HR department. We’ve decided to use Microsoft SQL Server 2012 given the nature of data to be stored because it will be more secure, and it also provides a suite of server maintenance tools to be left behind with the IT Department once the database and web application have been tested and accepted by university stakeholders.
During our preliminary meetings, CTU’s requirements were defined and adequately scoped to begin creation of the database. The following sections contain the business rules and entity tables developed during the preliminary meetings, as well as copies of all the SQL code used to build the database and create the Entity Relationship Diagram (ERD). Business Rules & Entity Tables
Business Rules:
· A student has a name, a birth date, and gender.
· You must track the date the student started at the university and his or her current GPA, as well as be able to inactivate him or her without deleting information.
· For advising purposes, store the student's background/bio information. This is like a little story.
· An advisor has a name and an e-mail address.
· Students are assigned to one advisor, but one advisor may service multiple students.
· A class has a class code, name, and description.
· You need to indicate the specific classes a student is taking/has taken at the university. Track the date the student started a specific class and the grade earned in that class.
· Each class that a student takes has 4 assignments. Each assignment is worth 100 points.Entity Tables:
SQL CODE:
Create Database:
CREATE DATABASE [Cameron_CTU]
CONTAINMENT = NONE
ON PRIMARY
( NAME = N'Cameron_CTU', FILENAME = N'c:\Program Files\Microsoft SQL Server\MSSQL11.SCAMERON_CTU\MSSQL\DATA\Cameron_CTU.mdf' , SIZE = 3072KB , FILEGROWTH = 1024KB )
LOG ON
( NAME = N'Cameron_CTU_log', FILENAME = N'c:\Program Files\Microsoft SQL Server\MSSQL11.SCAMERON_CTU\MSSQL\DATA\Cameron_CTU_.
This document provides instructions for experiments in a Database Management System laboratory course. It includes a list of 12 experiments covering topics like Data Definition Language commands, Data Manipulation Language commands, database design using ER modeling and normalization, and implementation of various database applications. It also provides details on the hardware and software requirements for the course, as well as the internal assessment structure including marks distribution.
This document discusses SQL skills and how queries can negatively impact server performance if not written efficiently. It covers topics like query plans, execution contexts, using parameters, indexing, handling large datasets, and external influences on SQL performance. Specific "bad" SQL examples are also provided and explained. The presenter's goal is to help developers optimize their SQL and prevent poorly written queries from bringing servers to their knees.
This document discusses SQL skills and how queries can negatively impact server performance if not written efficiently. It covers topics like query plans, execution contexts, using parameters, indexing, handling large datasets, and external influences on SQL performance. Specific "bad" SQL examples are also provided and analyzed. The presenter aims to help developers optimize their SQL and prevent poorly written queries from bringing servers to their knees.
Common Table Expressions (CTE) & Window Functions in MySQL 8.0oysteing
This document discusses common table expressions (CTE) and window functions in MySQL 8.0. It provides examples of using CTEs to improve readability, allow referencing tables multiple times, and refer to other CTEs. It also discusses recursive CTEs, window functions, and examples calculating aggregates like sums over partitions of rows.
Generating privacy-protected synthetic data using Secludy and MilvusZilliz
During this demo, the founders of Secludy will demonstrate how their system utilizes Milvus to store and manipulate embeddings for generating privacy-protected synthetic data. Their approach not only maintains the confidentiality of the original data but also enhances the utility and scalability of LLMs under privacy constraints. Attendees, including machine learning engineers, data scientists, and data managers, will witness first-hand how Secludy's integration with Milvus empowers organizations to harness the power of LLMs securely and efficiently.
Your One-Stop Shop for Python Success: Top 10 US Python Development Providersakankshawande
Simplify your search for a reliable Python development partner! This list presents the top 10 trusted US providers offering comprehensive Python development services, ensuring your project's success from conception to completion.
More Related Content
Similar to Set operators - derived tables and CTEs
Here are the key points about .NET:
- .NET is a software development platform from Microsoft that runs primarily on Windows. It introduces a new virtual machine called the Common Language Runtime (CLR) which compiles code into an intermediate language (IL) that can be executed on any operating system that supports .NET.
- Major languages supported include C#, Visual Basic .NET, and C++/CLI. These compile to IL rather than native machine code.
- The .NET Framework provides a large class library called Framework Class Library (FCL) which includes functionality for common tasks like database access, XML, networking, graphics etc.
- Major versions include 1.0 (released 2002), 1.1 (
SQL is a standard language for accessing and manipulating databases. It allows users to query, insert, update, and delete data. The document discusses SQL statements like SELECT, INSERT, UPDATE, DELETE and functions like JOIN, aggregate functions, and scalar functions. It provides examples of creating tables and manipulating data using DDL, DML, and DCL statements. Joins allow combining data from multiple tables based on common fields.
Oracle Database Administration I (1Z0-082) Exam Dumps 2024.pdfSkillCertProExams
• For a full set of 420+ questions. Go to
https://skillcertpro.com/product/oracle-database-administration-i-1z0-082-exam-questions/
• SkillCertPro offers detailed explanations to each question which helps to understand the concepts better.
• It is recommended to score above 85% in SkillCertPro exams before attempting a real exam.
• SkillCertPro updates exam questions every 2 weeks.
• You will get life time access and life time free updates
• SkillCertPro assures 100% pass guarantee in first attempt.
The document discusses various SQL commands and techniques. It provides explanations and examples of:
1) How to use the SPOOL command to output a SQL query to a text file. The SPOOL command directs query output to a file, and SPOOL OFF closes the file.
2) Common questions about SQL, including the differences between DDL, DML, and DCL commands, escaping special characters in queries, eliminating duplicate rows, generating primary keys, calculating time differences between dates, and adding to date values.
3) Techniques for counting distinct values or value ranges in a column, retrieving a specific row number from a table, and implementing IF-THEN-ELSE logic in a SQL
This document provides information about SQL queries using DML statements like INSERT, SELECT, UPDATE, DELETE. It includes examples of inserting data into a table using INSERT, selecting data from a table using SELECT, and selecting specific records using a WHERE clause. It also discusses using LIKE in the WHERE clause to filter results containing a substring. The objectives are to study SQL DML statements and design at least 10 queries using DML statements, operators, functions and set operators.
This document discusses common table expressions (CTEs) in MySQL 8.0. It begins with an introduction to CTEs, explaining how they provide an alternative to derived tables. The document then covers non-recursive and recursive CTEs. For non-recursive CTEs, it provides examples of finding the best and worst month of sales. For recursive CTEs, it demonstrates examples such as generating a sequence of numbers and traversing a employee hierarchy. The key benefits of CTEs over derived tables are also summarized, such as improved readability, ability to reference a CTE multiple times, and potential performance improvements from avoiding multiple materializations.
Charles WilliamsCS362Unit 3 Discussion BoardStructured Query Langu.docxchristinemaritza
Charles WilliamsCS362Unit 3 Discussion Board
Structured Query Language for Data Management 1
Structured Query Language for Data Management 36-04-17
Table of Contents
Phase 1- Database Design and DDL 3
Business Rules & Entity Tables 3
Entity Tables: 4
SQL CODE: 4
Screenshots: 8
Phase 2 – Security and DML 13
Task 1 14
Task 2 15
Task 3 16
Task 4 17
Task 5 18
Phase 3 - DML (Select) and Procedures 19
Task 1 19
Task 2 20
Task 3 21
Task 4 22
Task 5 23
Phase 4 – Architecture, Indexes 27
Step 1: CREATE TABLE [Degrees] 27
Step 2: Re-create ‘Classes’ TABLE to add ‘DegreeID’ column and INSERT 6 classes 29
Step 3: ALTER TABLE [Students] 31
Step 5: DML script to INSERT INTO the ‘Students’ table ‘DegreeID’ data 33
Step 6: Display ERD 36
Phase 5 – Views, Transactions, Testing and Performance 37
References 38
Phase 1- Database Design and DDL
I contracted to design and develop a database for CTU that will store individual and confidential university data. This database is required to give the back-end engineering to a front-end web application with an instinctive User/Interface (U/I) to be utilized by the college HR office. We've chosen to utilize Microsoft SQL Server 2012 given the way of information to be put away because it will be more secure, and it additionally gives a suite of server upkeep apparatuses to be deserted with the IT Department once the database and web application have been tried and acknowledged by college partners.
Amid our preparatory gatherings, CTU's necessities were characterized and enough perused to start making of the database. The accompanying areas contain the business tenets and element tables created amid the preparatory gatherings, and additionally duplicates of all the SQL code used to manufacture the database and make the Entity Relationship Diagram (ERD).
Business Rules & Entity Tables
Business Rules:
· A student has a name, a birth date, and gender.
· You must track the date the student started at the university and his or her current GPA, as well as be able to inactivate him or her without deleting information.
· For advising purposes, store the student's background/bio information. This is like a little story.
· An advisor has a name and an e-mail address.
· Students are assigned to one advisor, but one advisor may service multiple students.
· A class has a class code, name, and description.
· You need to indicate the specific classes a student is taking/has taken at the university. Track the date the student started a specific class and the grade earned in that class.
· Each class that a student takes has 4 assignments. Each assignment is worth 100 points.Entity Tables:
SQL CODE:
Create Database:
CREATE DATABASE [Cameron_CTU]
CONTAINMENT = NONE
ON PRIMARY
( NAME = N'Cameron_CTU', FILENAME = N'c:\Program Files\Microsoft SQL Server\MSSQL11.SCAMERON_CTU\MSSQL\DATA\Cameron_CTU.mdf' , SIZE = 3072KB , FILEGROWTH = 1024KB )
LOG ON
( NAME = N'Cameron_CTU_log', FILENAME = N'c:\Progra ...
This document discusses common table expressions (CTEs) in MySQL 8.0. It begins with an introduction to CTEs, explaining that they allow for subqueries to be defined before the main query similar to derived tables but with better performance and readability. It then provides examples of non-recursive and recursive CTEs. For non-recursive CTEs, it demonstrates finding the best and worst month of sales. For recursive CTEs, it shows examples of generating a sequence of numbers from 1 to 10 and generating missing dates in a date sequence. The document emphasizes that CTEs only need to be materialized once, improving performance over derived tables.
This document discusses new features in SQL Server including MERGE statements, table valued parameters, grouping sets, and FILESTREAM storage. MERGE statements allow inserting, updating, and deleting data in one statement based on matching or non-matching rows between two tables. Table valued parameters allow passing tables of data as parameters to stored procedures. Grouping sets enable grouping data by multiple columns in a single query. FILESTREAM storage integrates the database engine with the file system to allow storing large binary objects on disk for improved performance.
This document provides an overview of queries in Microsoft Access, including:
- Simple queries allow selecting records from one or more tables using criteria. Calculated fields can be created using the Expression Builder.
- More complex queries include grouping data, creating tables from queries, updating data, adding new records, and deleting records. Crosstab queries summarize and reformat data.
- The module teaches the concepts of queries, building queries visually, writing selection criteria, and using calculated fields and expressions. However, it does not cover everything about queries.
The document provides an introduction to the SQL language, including its main components of DML (Data Manipulation Language) and DDL (Data Definition Language). It discusses SQL concepts such as creating tables with data types, defining primary and foreign keys, and using basic queries with SELECT, FROM, WHERE and ORDER BY clauses.
The document discusses how to tune a query for better performance. It begins by explaining that the algorithm and approach are most important for performance and scalability. Writing procedural code should be avoided when possible in favor of set-based operations using SQL. Examples are provided of poorly written procedural code that could be improved by using SQL constructs instead. The document then demonstrates how to tune a sample query by adding relevant indexes and constraints based on the schema. Overall, the key points are to think in sets rather than procedurally, leverage SQL over procedural code, and understand how the schema and metadata impact query optimization.
Structured Query Language for Data Management 2 Sructu.docxjohniemcm5zt
Structured Query Language for Data Management 2
Sructured Query Language for Data Management 6
Table of Contents
Phase 1- Database Design and DDL 3
Business Rules & Entity Tables 3
Entity Tables: 4
SQL CODE: 4
Screenshots: 8
Phase 2 – Security and DML 13
Task 1 14
Task 2 15
Task 3 16
Task 4 17
Task 5 18
Phase 3 - DML (Select) and Procedures 19
Task 1 19
Task 2 20
Task 3 21
Task 4 22
Task 5 23
Phase 4 – Architecture, Indexes 27
Step 1: CREATE TABLE [Degrees] 27
Step 2: Re-create ‘Classes’ TABLE to add ‘DegreeID’ column and INSERT 6 classes 29
Step 3: ALTER TABLE [Students] 31
Step 5: DML script to INSERT INTO the ‘Students’ table ‘DegreeID’ data 33
Step 6: Display ERD 36
Phase 5 – Views, Transactions, Testing and Performance 37
References 38
Phase 1- Database Design and DDL
My team was recently contracted to design and develop a database for CTU that will store personal and confidential university data. This database is expected to provide the back-end architecture for a front-end web application with an intuitive User/Interface (U/I) to be used by the university HR department. We’ve decided to use Microsoft SQL Server 2012 given the nature of data to be stored because it will be more secure, and it also provides a suite of server maintenance tools to be left behind with the IT Department once the database and web application have been tested and accepted by university stakeholders.
During our preliminary meetings, CTU’s requirements were defined and adequately scoped to begin creation of the database. The following sections contain the business rules and entity tables developed during the preliminary meetings, as well as copies of all the SQL code used to build the database and create the Entity Relationship Diagram (ERD). Business Rules & Entity Tables
Business Rules:
· A student has a name, a birth date, and gender.
· You must track the date the student started at the university and his or her current GPA, as well as be able to inactivate him or her without deleting information.
· For advising purposes, store the student's background/bio information. This is like a little story.
· An advisor has a name and an e-mail address.
· Students are assigned to one advisor, but one advisor may service multiple students.
· A class has a class code, name, and description.
· You need to indicate the specific classes a student is taking/has taken at the university. Track the date the student started a specific class and the grade earned in that class.
· Each class that a student takes has 4 assignments. Each assignment is worth 100 points.Entity Tables:
SQL CODE:
Create Database:
CREATE DATABASE [Cameron_CTU]
CONTAINMENT = NONE
ON PRIMARY
( NAME = N'Cameron_CTU', FILENAME = N'c:\Program Files\Microsoft SQL Server\MSSQL11.SCAMERON_CTU\MSSQL\DATA\Cameron_CTU.mdf' , SIZE = 3072KB , FILEGROWTH = 1024KB )
LOG ON
( NAME = N'Cameron_CTU_log', FILENAME = N'c:\Program Files\Microsoft SQL Server\MSSQL11.SCAMERON_CTU\MSSQL\DATA\Cameron_CTU_.
This document provides instructions for experiments in a Database Management System laboratory course. It includes a list of 12 experiments covering topics like Data Definition Language commands, Data Manipulation Language commands, database design using ER modeling and normalization, and implementation of various database applications. It also provides details on the hardware and software requirements for the course, as well as the internal assessment structure including marks distribution.
This document discusses SQL skills and how queries can negatively impact server performance if not written efficiently. It covers topics like query plans, execution contexts, using parameters, indexing, handling large datasets, and external influences on SQL performance. Specific "bad" SQL examples are also provided and explained. The presenter's goal is to help developers optimize their SQL and prevent poorly written queries from bringing servers to their knees.
This document discusses SQL skills and how queries can negatively impact server performance if not written efficiently. It covers topics like query plans, execution contexts, using parameters, indexing, handling large datasets, and external influences on SQL performance. Specific "bad" SQL examples are also provided and analyzed. The presenter aims to help developers optimize their SQL and prevent poorly written queries from bringing servers to their knees.
Common Table Expressions (CTE) & Window Functions in MySQL 8.0oysteing
This document discusses common table expressions (CTE) and window functions in MySQL 8.0. It provides examples of using CTEs to improve readability, allow referencing tables multiple times, and refer to other CTEs. It also discusses recursive CTEs, window functions, and examples calculating aggregates like sums over partitions of rows.
Similar to Set operators - derived tables and CTEs (20)
Generating privacy-protected synthetic data using Secludy and MilvusZilliz
During this demo, the founders of Secludy will demonstrate how their system utilizes Milvus to store and manipulate embeddings for generating privacy-protected synthetic data. Their approach not only maintains the confidentiality of the original data but also enhances the utility and scalability of LLMs under privacy constraints. Attendees, including machine learning engineers, data scientists, and data managers, will witness first-hand how Secludy's integration with Milvus empowers organizations to harness the power of LLMs securely and efficiently.
Your One-Stop Shop for Python Success: Top 10 US Python Development Providersakankshawande
Simplify your search for a reliable Python development partner! This list presents the top 10 trusted US providers offering comprehensive Python development services, ensuring your project's success from conception to completion.
Have you ever been confused by the myriad of choices offered by AWS for hosting a website or an API?
Lambda, Elastic Beanstalk, Lightsail, Amplify, S3 (and more!) can each host websites + APIs. But which one should we choose?
Which one is cheapest? Which one is fastest? Which one will scale to meet our needs?
Join me in this session as we dive into each AWS hosting service to determine which one is best for your scenario and explain why!
FREE A4 Cyber Security Awareness Posters-Social Engineering part 3Data Hops
Free A4 downloadable and printable Cyber Security, Social Engineering Safety and security Training Posters . Promote security awareness in the home or workplace. Lock them Out From training providers datahops.com
In the realm of cybersecurity, offensive security practices act as a critical shield. By simulating real-world attacks in a controlled environment, these techniques expose vulnerabilities before malicious actors can exploit them. This proactive approach allows manufacturers to identify and fix weaknesses, significantly enhancing system security.
This presentation delves into the development of a system designed to mimic Galileo's Open Service signal using software-defined radio (SDR) technology. We'll begin with a foundational overview of both Global Navigation Satellite Systems (GNSS) and the intricacies of digital signal processing.
The presentation culminates in a live demonstration. We'll showcase the manipulation of Galileo's Open Service pilot signal, simulating an attack on various software and hardware systems. This practical demonstration serves to highlight the potential consequences of unaddressed vulnerabilities, emphasizing the importance of offensive security practices in safeguarding critical infrastructure.
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Tatiana Kojar
Skybuffer AI, built on the robust SAP Business Technology Platform (SAP BTP), is the latest and most advanced version of our AI development, reaffirming our commitment to delivering top-tier AI solutions. Skybuffer AI harnesses all the innovative capabilities of the SAP BTP in the AI domain, from Conversational AI to cutting-edge Generative AI and Retrieval-Augmented Generation (RAG). It also helps SAP customers safeguard their investments into SAP Conversational AI and ensure a seamless, one-click transition to SAP Business AI.
With Skybuffer AI, various AI models can be integrated into a single communication channel such as Microsoft Teams. This integration empowers business users with insights drawn from SAP backend systems, enterprise documents, and the expansive knowledge of Generative AI. And the best part of it is that it is all managed through our intuitive no-code Action Server interface, requiring no extensive coding knowledge and making the advanced AI accessible to more users.
5th LF Energy Power Grid Model Meet-up SlidesDanBrown980551
5th Power Grid Model Meet-up
It is with great pleasure that we extend to you an invitation to the 5th Power Grid Model Meet-up, scheduled for 6th June 2024. This event will adopt a hybrid format, allowing participants to join us either through an online Mircosoft Teams session or in person at TU/e located at Den Dolech 2, Eindhoven, Netherlands. The meet-up will be hosted by Eindhoven University of Technology (TU/e), a research university specializing in engineering science & technology.
Power Grid Model
The global energy transition is placing new and unprecedented demands on Distribution System Operators (DSOs). Alongside upgrades to grid capacity, processes such as digitization, capacity optimization, and congestion management are becoming vital for delivering reliable services.
Power Grid Model is an open source project from Linux Foundation Energy and provides a calculation engine that is increasingly essential for DSOs. It offers a standards-based foundation enabling real-time power systems analysis, simulations of electrical power grids, and sophisticated what-if analysis. In addition, it enables in-depth studies and analysis of the electrical power grid’s behavior and performance. This comprehensive model incorporates essential factors such as power generation capacity, electrical losses, voltage levels, power flows, and system stability.
Power Grid Model is currently being applied in a wide variety of use cases, including grid planning, expansion, reliability, and congestion studies. It can also help in analyzing the impact of renewable energy integration, assessing the effects of disturbances or faults, and developing strategies for grid control and optimization.
What to expect
For the upcoming meetup we are organizing, we have an exciting lineup of activities planned:
-Insightful presentations covering two practical applications of the Power Grid Model.
-An update on the latest advancements in Power Grid -Model technology during the first and second quarters of 2024.
-An interactive brainstorming session to discuss and propose new feature requests.
-An opportunity to connect with fellow Power Grid Model enthusiasts and users.
Introduction of Cybersecurity with OSS at Code Europe 2024Hiroshi SHIBATA
I develop the Ruby programming language, RubyGems, and Bundler, which are package managers for Ruby. Today, I will introduce how to enhance the security of your application using open-source software (OSS) examples from Ruby and RubyGems.
The first topic is CVE (Common Vulnerabilities and Exposures). I have published CVEs many times. But what exactly is a CVE? I'll provide a basic understanding of CVEs and explain how to detect and handle vulnerabilities in OSS.
Next, let's discuss package managers. Package managers play a critical role in the OSS ecosystem. I'll explain how to manage library dependencies in your application.
I'll share insights into how the Ruby and RubyGems core team works to keep our ecosystem safe. By the end of this talk, you'll have a better understanding of how to safeguard your code.
For the full video of this presentation, please visit: https://www.edge-ai-vision.com/2024/06/temporal-event-neural-networks-a-more-efficient-alternative-to-the-transformer-a-presentation-from-brainchip/
Chris Jones, Director of Product Management at BrainChip , presents the “Temporal Event Neural Networks: A More Efficient Alternative to the Transformer” tutorial at the May 2024 Embedded Vision Summit.
The expansion of AI services necessitates enhanced computational capabilities on edge devices. Temporal Event Neural Networks (TENNs), developed by BrainChip, represent a novel and highly efficient state-space network. TENNs demonstrate exceptional proficiency in handling multi-dimensional streaming data, facilitating advancements in object detection, action recognition, speech enhancement and language model/sequence generation. Through the utilization of polynomial-based continuous convolutions, TENNs streamline models, expedite training processes and significantly diminish memory requirements, achieving notable reductions of up to 50x in parameters and 5,000x in energy consumption compared to prevailing methodologies like transformers.
Integration with BrainChip’s Akida neuromorphic hardware IP further enhances TENNs’ capabilities, enabling the realization of highly capable, portable and passively cooled edge devices. This presentation delves into the technical innovations underlying TENNs, presents real-world benchmarks, and elucidates how this cutting-edge approach is positioned to revolutionize edge AI across diverse applications.
Salesforce Integration for Bonterra Impact Management (fka Social Solutions A...Jeffrey Haguewood
Sidekick Solutions uses Bonterra Impact Management (fka Social Solutions Apricot) and automation solutions to integrate data for business workflows.
We believe integration and automation are essential to user experience and the promise of efficient work through technology. Automation is the critical ingredient to realizing that full vision. We develop integration products and services for Bonterra Case Management software to support the deployment of automations for a variety of use cases.
This video focuses on integration of Salesforce with Bonterra Impact Management.
Interested in deploying an integration with Salesforce for Bonterra Impact Management? Contact us at sales@sidekicksolutionsllc.com to discuss next steps.
Digital Marketing Trends in 2024 | Guide for Staying AheadWask
https://www.wask.co/ebooks/digital-marketing-trends-in-2024
Feeling lost in the digital marketing whirlwind of 2024? Technology is changing, consumer habits are evolving, and staying ahead of the curve feels like a never-ending pursuit. This e-book is your compass. Dive into actionable insights to handle the complexities of modern marketing. From hyper-personalization to the power of user-generated content, learn how to build long-term relationships with your audience and unlock the secrets to success in the ever-shifting digital landscape.
Building Production Ready Search Pipelines with Spark and MilvusZilliz
Spark is the widely used ETL tool for processing, indexing and ingesting data to serving stack for search. Milvus is the production-ready open-source vector database. In this talk we will show how to use Spark to process unstructured data to extract vector representations, and push the vectors to Milvus vector database for search serving.
Best 20 SEO Techniques To Improve Website Visibility In SERPPixlogix Infotech
Boost your website's visibility with proven SEO techniques! Our latest blog dives into essential strategies to enhance your online presence, increase traffic, and rank higher on search engines. From keyword optimization to quality content creation, learn how to make your site stand out in the crowded digital landscape. Discover actionable tips and expert insights to elevate your SEO game.
A Comprehensive Guide to DeFi Development Services in 2024Intelisync
DeFi represents a paradigm shift in the financial industry. Instead of relying on traditional, centralized institutions like banks, DeFi leverages blockchain technology to create a decentralized network of financial services. This means that financial transactions can occur directly between parties, without intermediaries, using smart contracts on platforms like Ethereum.
In 2024, we are witnessing an explosion of new DeFi projects and protocols, each pushing the boundaries of what’s possible in finance.
In summary, DeFi in 2024 is not just a trend; it’s a revolution that democratizes finance, enhances security and transparency, and fosters continuous innovation. As we proceed through this presentation, we'll explore the various components and services of DeFi in detail, shedding light on how they are transforming the financial landscape.
At Intelisync, we specialize in providing comprehensive DeFi development services tailored to meet the unique needs of our clients. From smart contract development to dApp creation and security audits, we ensure that your DeFi project is built with innovation, security, and scalability in mind. Trust Intelisync to guide you through the intricate landscape of decentralized finance and unlock the full potential of blockchain technology.
Ready to take your DeFi project to the next level? Partner with Intelisync for expert DeFi development services today!
leewayhertz.com-AI in predictive maintenance Use cases technologies benefits ...alexjohnson7307
Predictive maintenance is a proactive approach that anticipates equipment failures before they happen. At the forefront of this innovative strategy is Artificial Intelligence (AI), which brings unprecedented precision and efficiency. AI in predictive maintenance is transforming industries by reducing downtime, minimizing costs, and enhancing productivity.
2. Welcome
Welcome to all those joining us remotely.
For any questions via Google On Air Broadcasts, we will
address most of these at the end of the training.
Training provided by Emergency Reporting
http://EmergencyReporting.com
Presented by Steve Stedman and Aaron Buma
3. Live Broadcast
Using Google On Air Broadcasts
There is about a 40 to 50 second delay from live to what
you see.
We are still learning how to properly use Google On Air
Broadcasts. Please be patient.
Session will be available on my YouTube Channel about
an hour after it the presentation ends.
http://SteveStedman.com/YouTube
4. Questions
We will have time for questions at the end of the session.
Q&A available via Google On Air Hangout panel. Click the
3x3 grid icon near the top right, then select Q&A to see
what people are asking, or to ask your own question.
When you ask a question, it shows up for us about 40 to 50
seconds delayed.
8. UNION TYPES
UNION
Requires same data types and number of columns
Acts like a ‘distinct’, it won’t return duplicates
UNION ALL
Similar to UNION, but will return duplicates
ORDER BY – is applied to entire results
Up to 256 queries can be “UNION”ed together
9. INTERSECT and EXCEPT
Same field and data type matching as UNION
Only used with two tables
INTERSECT –
Results that only match all tables
EXCEPT- Results from the first query,
not matching results from the second
17. CTE Book
Published May 2013
Today’s topic comes from Chapter 1, 2, 3, 4, 6,
7 and 9
Of
SQL Server Common Table
Expression
18. CTE – Agenda
Introduction to Memory Tables and CTEs
Simple CTE
CTE Instead of a Derived Table
Multiple CTE in a Query
Data Paging
CTEs in Stored Procedures, Functions and Views
Introduction To Recursive CTEs
20. Virtual Tables
Derived Table
Sub query
Views
Temporary Named Result Set
Temp Tables
Table Variables
Common Table Expressions
Memory Tables SELECT *
FROM (SELECT id,
department,
parent
FROM Departments) as Dept;
CREATE VIEW [dbo].[DeptView]
AS
SELECT id, department, parent
FROM Departments;
GO
SELECT q1.department,
q2.department AS subDept
FROM DeptView q1
INNER JOIN DeptView q2
ON q1.id = q2.parent
WHERE q1.parent IS NULL;
CREATE TABLE #deptTempTable (
id int,
department VARCHAR (200),
parent int
);
DECLARE @deptTableVariable TABLE(
id int,
department VARCHAR (200),
parent int
);
21. A type of a virtual table
Similar to the ease of a temporary table
Sort of like a derived table
Like a temporary named result set
Acts like a temporary view, or a run time view
What is a CTE
22. Availability of CTEs
TRANSACT SQL feature that I wish I had
learned about 10 years ago, CTE’s were
introduced in SQL Server 2005
All versions of SQL Server since SQL 2005
and all variations of SQL Server support
CTEs
CTEs are available in SQL Azure
23. Why Use Common Table
Expressions?
Simplify your query – test one part at a time
Recursion
Computer Science: When a function calls itself
SQL Server: When a query calls itself
Make derived table queries more readable
Alternative to a temp table or a table variable
24. CTE Syntax - WITH
Queries start with WITH not SELECT
Can be confusing if you are assuming that any query to
select data would start with a SELECT
The scope of the CTE is confined to a single query
A CTE just seems a little weird, until you master the syntax
25. Simple CTE Syntax
;WITH expression_name [(column_name[,...n])]
AS
(
CTE_query_definition
)
SELECT <column_list>
FROM expression_name;
29. CTE Instead of a Derived Table
Simplifies the query – allows for cleaner code
Does not improve the performance
More value for large derived table queries in that the TSQL
is cleaner and easier to read and understand
Eliminates accidents by duplicating derived table queries
TSQL code
30. Derived Table Without a CTE
SELECT q1.department, q2.department
FROM (SELECT id, department, parent
FROM Departments) AS q1
INNER JOIN (SELECT id, department, parent
FROM Departments) AS q2
ON q1.id = q2.parent
WHERE q1.parent IS NULL;
31. Convert a Derived Table to a CTE
Find the first occurrence of the derived table query to be
broken out. Create a name for it and add “CTE” to the name.
Copy the derived table definition, including the parentheses,
and leave the new name as the placeholder.
Paste the query, copied earlier, above the SELECT statement.
At the top of the query add the CTE declaration using the same
name from step 1.
Find all other occurrences of the same derived table query and
replace them with the CTE name.
Clean up the formatting and test the query.
32. CTE for Derived Table Re-use
;WITH deptCTE (id, department, parent) AS
(SELECT id, department, parent
FROM Departments)
SELECT q1.department, q2.department
FROM deptCTE q1
INNER JOIN deptCTE q2 on q1.id = q2.parent
WHERE q1.parent is null;
34. CTE Instead of a Derived Table
Summary
Most derived tables can be easily converted to a CTE
Copy and paste errors can be reduced by using a CTE
Using a CTE doesn’t improve the performance over a
similar query written with derived tables
For a CTE that is referenced multiple times the CTE query
is not reused, it is executed multiple times
36. Multiple CTE’s In A Single Query
You can include multiple CTE's by comma separating them:
;WITH firstCTE AS
(query goes here)
,secondCTE AS
(second query goes here)
SELECT * FROM firstCTE
INNER JOIN secondCTE on ...
37. Steps to add a Second CTE
1. Add a comma at the end of the first CTE, after the closing
parentheses.
2. After the comma, on the next line, declare the name of the new
CTE.
3. After the name of the new CTE add the optional columns
declaration.
4. Add the AS keyword followed by opening and closing
parentheses.
5. Inside of the parentheses add the new CTE query.
6. Call the CTE query from the outer SELECT statement.
38. Demo: Multiple CTE
;WITH Fnames (Name) AS
(
SELECT 'John' UNION SELECT 'Mary' UNION SELECT 'Bill'
)
, Lnames (Name) AS
(
SELECT 'Smith' UNION SELECT 'Gibb' UNION SELECT 'Jones'
)
SELECT F.Name FirstName, L.Name LastName
FROM Fnames F
CROSS JOIN Lnames AS L;
39. Nested CTE’s
Russian Dolls – матрёшки
Pronounced Ma-Trosh-Key.
A Nested CTE query can only reference itself or CTE
queries declared earlier in the query.
40. Nested CTE Example;WITH cte0 AS
(
SELECT 1 AS num
)
, cte1 AS
(
SELECT num + 1 AS num
FROM cte0
)
, cte2 AS
(
SELECT num + 1 AS num
FROM cte1
)
SELECT *
FROM cte2;
43. Data Paging
To achieve data paging without CTE it usually involves
selecting TOP x, then TOP 2x then top 3x, each time taking
longer and longer to get to the data that is needed.
Data paging can be simplified and not a challenge to create
with CTE’s.
TSQL 2012 introduces the OFFSET and FETCH keywords
which is easier to use than a CTE for data paging, and more
efficient.
47. Demo: Data Paging
;WITH TablesAndColumns AS (
SELECT OBJECT_NAME(sc.object_id) AS TableName,
name AS ColumnName,
ROW_NUMBER()
OVER (ORDER BY object_name(sc.object_id))
AS Row
FROM sys.columns sc )
SELECT *
FROM TablesAndColumns
WHERE Row BETWEEN (@pageNum - 1) * @pageSize + 1
AND @pageNum * @pageSize ;
48. Demo: SQL Server 2012 and
Beyond Data Paging
SELECT OBJECT_NAME(sc.object_id) AS TableName,
name AS ColumnName
FROM sys.columns sc
ORDER BY TableName
OFFSET (@pageNum - 1) * @pageSize ROWS
FETCH NEXT @pageSize ROWS ONLY;
•An alternative to CTE’s for data paging if you are using SQL
Server 2012 or newer
54. 4. Recursive CTE Considered recursive when the CTE references itself
Recursion stops
When the recursive query produces no results
Or specify MAXRECURSION
Uses
Hierarchical listing of categories
Recursive calculations
Much, much more…
55. Recursion Overview Sum the numbers from 1 to 10 without recursion
55 = 10 + 9 + 8 + 7 + 6 + 5 + 4 +3 + 2 + 1
Sum the numbers from 1 to 10 recursively
55 = 10 + (sum of numbers 1 to 9)
55 = 10 + (9 + (sum of numbers 1 to 8))
55 = 10 + (9 + (8 + (sum of numbers 1 to 7)))
Eventually we get to:
55 = 10 + (9 + (8 + (7 + (6 + (5 + (4 + (3 + (2 + 1))))))))
56. Recursive Terminology
Anchor Query
Start the recursion
One or more anchor queries
Recursive Query
The part that repeats
One or more recursive queries
MAXRECURSION
The number of times to repeat the recursive query
Default is 100
MAXRECURSION of 0 implies no maximum
57. Demo: Recursive CTE
;WITH DepartmentCTE(DeptId, Department, Parent, Lvl)
AS
Step 1. Declare the CTE and Columns
58. Demo: Recursive CTE
;WITH DepartmentCTE(DeptId, Department, Parent, Lvl)
AS
( SELECT id AS DeptId, Department, parent, 0 AS Lvl
FROM Departments
WHERE parent IS NULL
Step 2 – Add the Anchor Query
59. Demo: Recursive CTE
;WITH DepartmentCTE(DeptId, Department, Parent, Lvl)
AS
( SELECT id AS DeptId, Department, parent, 0 AS Lvl
FROM Departments
WHERE parent IS NULL
UNION ALL
Step 3 – Add the UNION ALL to connect to the recursive query
60. Demo: Recursive CTE
;WITH DepartmentCTE(DeptId, Department, Parent, Lvl)
AS
( SELECT id AS DeptId, Department, parent, 0 AS Lvl
FROM Departments
WHERE parent IS NULL
UNION ALL -- and now for the recursive part
SELECT d.id AS DeptId, d.Department, d.parent,
DepartmentCTE.Lvl + 1 AS Lvl
FROM Departments d
INNER JOIN DepartmentCTE
ON DepartmentCTE.DeptId = d.parent)
Step 4 – Add the recursive Query
61. Demo: Recursive CTE;WITH DepartmentCTE(DeptId, Department, Parent, Lvl)
AS
( SELECT id AS DeptId, Department, parent, 0 AS Lvl
FROM Departments
WHERE parent IS NULL
UNION ALL -- and now for the recursive part
SELECT d.id AS DeptId, d.Department, d.parent,
DepartmentCTE.Lvl + 1 AS Lvl
FROM Departments d
INNER JOIN DepartmentCTE
ON DepartmentCTE.DeptId = d.parent)
SELECT *
FROM DepartmentCTE
ORDER BY parent;
63. Recursive CTE Notes Recursion stops
When the recursive query produces no results
Or specify MAXRECURSION
Using TSQL functions for recursion allows for 32 levels of
recursion
Using CTE for recursion allows for 32767 levels of recursion in
the MAXRECURSION option, but much more if you set
MAXRECURSION to 0.
I have confirmed up to 100,000,000 levels of recursion.
64. Download the samples and there
are many additional CTE examples
at the end of the file.
Bonus Material
65. Quiz 1. CTE Executions
As a named result set, the CTE is only run once even if
it is referenced multiple times in a query.
True or False?
FALSE The CTE is executed once for EACH time
that it is referenced in a query.
66. Quiz 1. CTE Executions Explained
;WITH deptCTE(id, department, parent) AS
(SELECT id, department, parent
FROM Departments)
SELECT q1.department, q2.department
FROM deptCTE q1
INNER JOIN deptCTE q2 on q1.id = q2.parent
WHERE q1.parent is null;
In this example the deptCTE is executed twice
67. Quiz 2. CTEs are proprietary
CTEs are proprietary to Microsoft SQL Server.
True or False?
FALSE Common Table Expressions are
supported by several major database platforms,
among them PostgreSQL, DB2, Oracle and SQL
Server, defined in SQL-99 spec
68. Quiz 3. CTE and Hierarchical Queries
CTEs are a great way to create recursive
hierarchical queries.
True or False?
TRUE Recursive hierarchical queries are easy to
write with a CTE. CTE’s save time, are easy to
follow, and work great for hierarchical data.
69. Quiz 5. Database Versions
SQL Server only supports CTE’s on SQL Server
Enterprise Edition 2008R2 and newer.
True or False?
FALSE Common Table Expressions have
been supported since SQL Server 2005 and
are available in all versions.
70. Quiz 6. CTEs and Nesting
CTEs can be nested and one CTE can reference
an earlier CTE.
True or False?
TRUE Common Table Expressions can be
nested. Just define multiple CTE’s and
reference an earlier CTE from a later one.
71. Quiz 7. Indexing CTEs
Indexes can be added to CTEs to boost performance.
True or False?
FALSE A Common Table Expression is a temporary,
"inline" view - you cannot add an index to a CTE.
72. Quiz 8. VIEW vs CTE
Which performs better, a non-recursive CTE or a
VIEW?
They are the same.
The big gain is the recursive CTE, which you can’t
achieve with a view.
73. Quiz 9. CTE’s and Data Paging
CTE’s are a great way to do Data Paging for a result grid.
True or False
It Depends…...
SQL Server 2012 and 2014 have the new OFFSET and
FETCH clause on select statements, which is easier
than CTE’s. For 2005, 2008 and 2008R2 the CTE is the
best option.
74. Quiz 10. CTE’s and TempDB
CTE’s are similar to Temp Tables or Table Variables in
their use of TempDB?
True or False
FALSE Temp Tables and Table Variables both
use TempDB, CTE’s do not…...
See my blog posting for all the details on this one.
http://stevestedman.com/?p=2053
It is more than we have time to prove today.
75. Quiz 11:
INTERSECT can be replaced with:
An UPDATE statement
A LEFT JOIN
An INNER JOIN
An INNER JOIN with DISTINCT
76. Quiz 12:
EXCEPT can be replaced with:
An UPDATE statement
A LEFT JOIN, filtering on NULL join column
An INNER JOIN
An INNER JOIN with DISTINCT
77. Quiz 13:
With tables that have many duplicates, which will
return more rows:
UNION
UNION ALL
79. For More Information
Visit http://EmergencyReporting.com to find out more
about Emergency Reporting.
Aaron on the web
http://AaronBuma.com
Twitter: @AaronDBuma
Steve on the web
http://SteveStedman.com
twitter: @SqlEmt
80. Tune in next week
Thursday 2/17 at 9:00am (pacific time).
Topics
Derived Table Queries (ie Subqueries)
Correlated Sub Queries
Sub Query Extensions (ANY, ALL, SOME)
Exists
OUTPUT Clause