• Home
  • SQL Server
    • Articles
    • T-SQL Puzzles
    • Output Puzzles
    • Interview Questions
    • Performance Tuning
    • SQL SERVER On Linux
    • Resources
  • SSRS
    • SSRS Articles
    • Interview Questions
  • SSAS
    • SSAS Articles
    • DAX
  • SQL Puzzles
  • Interview Questions
    • SQL Interview Questions
    • Data Interview Questions
  • Python Interview Puzzles
  • New Features(SQL SERVER)
    • SQL SERVER 2017
    • SQL SERVER 2016
    • SQL SERVER On Linux
  • Social
    • Expert Exchange
      • Top Expert in SQL
      • Yearly Award
      • Certifications
      • Achievement List
      • Top Expert of the Week
    • HackerRank (SQL)
    • StackOverflow
    • About Me
      • Contact Me
      • Blog Rules

Improving my SQL BI Skills

Improving my SQL BI Skills

Daily Archives: July 6, 2015

T-SQL Query | [ Minus -1 or Minimum Child Puzzle ]

06 Monday Jul 2015

Posted by Pawan Kumar Khowal in T SQL Puzzles

≈ 2 Comments

Tags

Complex SQL Challenges, complex sql statement(puzzle), Complex TSQL Challenge, Divide rows into two columns, Interesting Interview Questions, Interview Qs.SQL SERVER Questions, Interview questions on Joins, Interview Questions on SQL, InterviewQuestions, InterviewQuestions for SQL, Joins, Joins Interview questions, Joins Puzzle, Khowal, last non null puzzle, Learn complex SQL, Learn SQL, Learn T-SQL, Objective Puzzle, Pawan, Pawan Khowal, Pawan Kumar, Pawan Kumar Khowal, PL/SQL Challenges, Prev Value puzzle, Previous value puzzle, puzzle sql developer, Puzzles, Queries for SQL Interview, SELECT Puzzle, SQL, SQL 2012, SQL 2014, SQL 2014 Interview Questions, SQL Challenge, SQL Challenges, SQL Interview Questions, SQL Joins, SQL pl/sql puzzles, SQL Puzzles, SQL Queries, SQL Quiz, SQL Server Database, SQL SERVER Interview questions, SQL Skills, SQL Sudoku, SQL Top clause, SQL Trikcy question, sql/database interview for puzzle sql developer, SQLSERVER, T SQL Puzzles, T-SQL Challenge, T-SQL Query | [ The Complex Week Puzzle ], The Biggest Gap Puzzle, The Gap Puzzle, The Gap Puzzle Puzzle, The Tree Puzzle, TOP Clause, Tough SQL Challenges, Tough SQL Puzzles, Tricky Questions, TSQL, TSQL Challenge, TSQL Challenges, TSQL Interview questions, TSQL Queries, Week puzzle


T-SQL Query | [ Minus -1 or Minimum Child Puzzle ]

Puzzle Description

  1. We have 2 tables called MinusParent & MinusChildren.
  2. We have to find out ChildServiceId for each parentId present in MinusChildren Table. Well there are some rules to pick ChildServiceId. They are-
  3. Rule1#- If all ChildServiceId values for a parentId are -1 then we have to pick -1 as ChildServiceID and minimum childId corresponding to that parentID. E.g. – In case of ParentID = 1 we need following values

ChildID = 101,  ChildServiceID = -1

4.  Rule 2#- If a single childServiceId has a non -1 value for a ParentId, then we have to pick that value as a ChildServiceId and its ChildId. E.g. In case of ParentId = 2, We need following values

ChildID = 202,  ChildServiceID = 23

5.  Rule 3# – If there are multiple non -1 values present for a single ParentId then we have to pick the minimum childId and its corresponding childServiceId. E.g. In case of ParentId = 4, we  need following values

ChildID = 402,  ChildServiceID = 23

6. Please check out the sample input and expected output for detail

Pawan Kumar Khowal - Minus -1 Or Minimum Child Puzzle

Pictorial presentation of the puzzle.

Sample Input

MinusParent

ParentID Value
1 A
2 B
3 C
4 D
5 E
6 F

MinusChildren

ChildId ParentID ChildServiceID Timestampes
101 1 -1 00:46.8
102 1 -1 00:46.8
103 1 -1 00:46.8
104 1 -1 00:46.8
105 1 -1 00:46.8
201 2 -1 00:46.8
202 2 23 00:46.8
203 2 -1 00:46.8
204 2 -1 00:46.8
205 2 -1 00:46.8
301 3 -1 00:46.8
302 3 -1 00:46.8
303 3 -1 00:46.8
304 3 -1 00:46.8
305 3 14 00:46.8
401 4 -1 00:46.8
402 4 23 00:46.8
403 4 25 00:46.8
404 4 -1 00:46.8
501 5 21 00:46.8
502 5 23 00:46.8
601 6 -1 00:46.8

Expected Output

ParentID Value ChildId ChildServiceId
1 A 101 -1
2 B 202 23
3 C 305 14
4 D 402 23
5 E 501 21
6 F 601 -1

Rules/Restrictions

  • The solution should be should use “SELECT” statement or “CTE”.
  • Add your solution(s) in the comments section or send you solution(s) topawankkmr@gmail.com

Script

Use the below script to generate the source table and fill them up with the sample data.

--

CREATE TABLE MinusParent
(
     ParentID INT PRIMARY KEY
     ,Value VARCHAR(10)
)
GO


INSERT INTO MinusParent(ParentID,Value)
VALUES (1,'A'),(2,'B'),(3,'C'),(4,'D'),(5,'E'),(6,'F')
GO

CREATE TABLE MinusChildren
(
     ChildId INT 
     ,ParentID INT REFERENCES MinusParent(ParentID)
     ,ChildServiceID INT
     ,Timestampes DATETIME
     ,PRIMARY KEY(ChildId,ParentId)
)
GO


INSERT INTO MinusChildren
VALUES  (101,1,-1,GETDATE()),(102,1,-1,GETDATE()),(103,1,-1,GETDATE()),(104,1,-1,GETDATE()),(105,1,-1,GETDATE()),
           (201,2,-1,GETDATE()),(202,2,23,GETDATE()),(203,2,-1,GETDATE()),(204,2,-1,GETDATE()),(205,2,-1,GETDATE()),
           (301,3,-1,GETDATE()),(302,3,-1,GETDATE()),(303,3,-1,GETDATE()),(304,3,-1,GETDATE()),(305,3,14,GETDATE()),
           (401,4,-1,GETDATE()),(402,4,23,GETDATE()),(403,4,25,GETDATE()),(404,4,-1,GETDATE()),
           (501,5,21,GETDATE()),(502,5,23,GETDATE()),
           (601,6,-1,GETDATE())

GO

CREATE NONCLUSTERED INDEX Ix_ParentID ON MinusChildren (ParentID)
GO

CREATE NONCLUSTERED INDEX Ix_Filtered_ParentID_ChildId_ChildServiceId ON MinusChildren (ParentID,ChildId,ChildServiceId)
WHERE ChildServiceId <> -1
GO


--

Update July 7 | Solution1 – Pawan Kumar Khowal

--

SET STATISTICS IO ON

SELECT        P.ParentID , P.Value 
            , ISNULL(D.ChildId,D1.ChildId) ChildId , ISNULL(ChildServiceID,-1) ChildServiceId 
FROM MinusParent p
OUTER APPLY
     (
           SELECT TOP (1) c.ChildId, c.ChildServiceID 
           FROM  MinusChildren c
           WHERE p.ParentID = c.ParentID AND c.ChildServiceID <> -1
           ORDER BY ChildId ASC       
     ) AS D
CROSS APPLY
     (    
           SELECT MIN(ChildId) ChildId FROM MinusChildren m3 WHERE m3.ParentID = p.ParentID           
     ) AS D1

--

Add a comment if you have any other solution in mind. We all need to learn. Keep Learning

Http://MSBISkills.com

Pawan Kumar Khowal

Execution/Query Plan Operator – The Sort Operator – Part II, Which sorting algorithms used by SQL Server? Is it blocking or non-blocking?

06 Monday Jul 2015

Posted by Pawan Kumar Khowal in SQL Performance Tuning

≈ Leave a comment

Tags

26 performance tuning questions and solutions, A block-sorting lossless data compression algorithm, Are "bad" statistics the reason my query is slow?, Avoiding Sort task in Execution Plan, Bad performance of SQL query due to ORDER BY clause, Blocked sort-based indexing, but the execution plan is still showing a distinct sort, Case in order clause causes bad page queries, Collapse, Estimated Execution Plan SQL Server Sort?, Execution plan - Sort Operator, How to tune SQL queries, How to understand SQL Server 2008 Execution Plan *sort*?, Indexing for Sort Performance, Interview questions for SQL Server Performance Tuning, Looking for SQL Optimization Interview Questions, performance sql server, Performance tips for faster SQL queries, Performance Tuning, Performance Tuning for SQL Server, Performance Tuning the Whole Query Plan, Query Optimization, Query Performance Tuning, Showplan Operator, Showplan Operator of the Week - SORT, ShowPlan Operator of the Week - Split, Sort, Sort - Is it Really a Blocking Iterator?, Sort operation in execution plan, Sort Showplan Operator, sorting - Blocking sort operators, SQL Complex Queries, SQL Optimization Interview Questions, sql performance, sql performance and tuning, sql performance explained pdf, sql performance tips, SQL Performance Tuning, sql performance tuning and optimization, sql performance tuning interview questions, sql performance tuning tips, SQL Query Optimizer, SQL Query Tuning or Query Optimization, sql server - Optimizing SQL queries by removing Sort, sql server - Why is there a sort showing up in my execution, SQL SERVER Interview questions, SQL server optimization interview questions and answers, sql server performance query, sql server performance slow, SQL Server Performance Tuning, SQL Server Performance Tuning Tips, SQL SERVER Tips, SQL Tuning Overview, The blocking nature of aggregates, Tips for SQL Database Tuning and Performance, Top 10 performance tuning tips for relational databases, Ways to minimize sort operations, with no ORDER BY clause


Execution Plan Operator – Properties, Types – Blocking / Non-Blocking?

Download PDF – Execution Plan – The Sort Operator – II, Which sorting algorithms used by SQL Server? Is it blocking or non-blocking?

Notes only

In this post I would like to talk sorting algorithms SQL Server uses for sorting. Well SQL Server uses 2 algorithms (or their flavours) to sort data. They are

• Quick Sort
• Merge Sort

It’s actually a matter of WHERE the data is when it’s being sorted. If & while the data is in memory, Quicksort is used.

If and when a tempDB spill occurs, an on-disk Merge Sort takes place.

SQL Server begins sorting in memory using Quick Sort algorithm. Memory grant required in this case = 200% * Input Size. If the memory grant is increased it will spills everything (Entire immediate sort and remaining input rows). After that the sorting will be completed on disk using Merge Sort algorithm.

Pawan Kumar Khowal - Execution Plan - The Sort Operator 1
Picture – Sorting Algorithms

Now what is Memory grant fraction – It is a number between 0 and 1. 1 means 100% of the granted memory. One can view this by right clicking the sort operator and looking in the properties window. The example below was taken from a query with only a single Sort operator, so it has the full query workspace memory grant available during both input and output phases

Pawan Kumar Khowal - Execution Plan - The Sort Operator 2

Picture – showing Memory grant fraction-

SQL Server has two kinds of execution plan operators. They are

• Blocking
• Non-blocking

For details about blocking and non-blocking operators click here – https://msbiskills.com/2015/07/05/execution-plan-operator-properties-types-blocking-non-blocking/

Now we know that Sort is a blocking operator, as it is very clear that unless we have all the data how can we sort as we don’t know which row will be on the top and which one at the bottom. Now let’s see the below query and is execution plan.

--


USE AdventureWorks2012
GO

SELECT * FROM Production.TransactionHistory
ORDER BY TransactionDate


--

Pawan Kumar Khowal - Execution Plan - The Sort Operator 3

Picture showing execution plan – The sort operator and the parallelism.

This is a parallel plan; all the operators are working in parallel (Parallelism – is a vast topic, shall cover this basics about this in upcoming posts) but the root iterator. Now we know that sort is a blocking operator and we have parallel symbol inside it. That is because Sort iterator has to consume all the input rows (In Open() Method) before it starts sorting but it starts producing output rows once the final run starts. Now let’s check the properties of sort operator and different threads to verify actually whether sort happens in parallel or not? Here the data on each thread is sorted separately and then Gather streams takes all the inputs and combine then together into a single stream.

There are eight threads present in the sort iterator properties because my laptop is an 8 core laptop. Basically numbers of threads are determined by MAXDOP (Maximum degree of Parallelism) for the plan.

Pawan Kumar Khowal - Execution Plan - The Sort Operator 4

Picture showing sort operator properties – Threads.

Summary
1. Sort is a blocking operator. It starts producing output rows once the final run starts.
2. Sort is not a parallel aware iterator
3. It uses Quick Sort and Merge Sort (or their Variants internally) to sort data.
4. You can fix the Sort by creating an Index, but always consider whether you really need that or not. If you have other queries which might get affected by this heavily.

That’s all folks; I hope you’ve enjoyed learning about Sort operator and its details, and I’ll see you soon with more “Performance Tuning” articles.

Thanks!

Pawan Kumar Khowal

MSBISKills.com

Share this

  • LinkedIn
  • Facebook
  • Twitter
  • WhatsApp
  • Email

Blog Stats

  • 1,084,484 hits

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 1,131 other subscribers

Pawan Khowal

502 SQL Puzzles with answers

Achievement - 500 PuzzlesJuly 18, 2018
The big day is here. Finally presented 500+ puzzles for SQL community.

200 SQL Server Puzzle with Answers

The Big DayAugust 19, 2016
The big day is here. Completed 200 SQL Puzzles today

Archives

July 2015
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  
« Jun   Aug »

Top Articles

  • pawankkmr.wordpress.com/2…
  • pawankkmr.wordpress.com/2…
  • pawankkmr.wordpress.com/2…
  • pawankkmr.wordpress.com/2…
  • pawankkmr.wordpress.com/2…

Archives

  • October 2020 (29)
  • September 2018 (2)
  • August 2018 (6)
  • July 2018 (25)
  • June 2018 (22)
  • May 2018 (24)
  • April 2018 (33)
  • March 2018 (35)
  • February 2018 (53)
  • January 2018 (48)
  • December 2017 (32)
  • November 2017 (2)
  • October 2017 (20)
  • August 2017 (8)
  • June 2017 (2)
  • March 2017 (1)
  • February 2017 (18)
  • January 2017 (2)
  • December 2016 (5)
  • November 2016 (23)
  • October 2016 (2)
  • September 2016 (14)
  • August 2016 (6)
  • July 2016 (22)
  • June 2016 (27)
  • May 2016 (15)
  • April 2016 (7)
  • March 2016 (5)
  • February 2016 (7)
  • December 2015 (4)
  • October 2015 (23)
  • September 2015 (31)
  • August 2015 (14)
  • July 2015 (16)
  • June 2015 (29)
  • May 2015 (25)
  • April 2015 (44)
  • March 2015 (47)
  • November 2012 (1)
  • July 2012 (8)
  • September 2010 (26)
  • August 2010 (125)
  • July 2010 (2)

Article Categories

  • Analysis Services (6)
    • DAX (6)
  • Data (2)
    • Data warehousing (2)
  • Integration Services (2)
  • Magazines (3)
  • Python (29)
  • Reporting Services (4)
  • SQL SERVER (820)
    • Download SQL Interview Q's (212)
    • SQL Concepts (323)
    • SQL Performance Tuning (155)
    • SQL Puzzles (331)
    • SQL SERVER 2017 Linux (6)
    • SQL Server Interview Questions (308)
    • SQL SERVER Puzzles (332)
    • T SQL Puzzles (547)
    • Tricky SQL Queries (439)
  • UI (30)
    • ASP.NET (5)
    • C# (13)
    • CSS (9)
    • OOPS (3)
  • Uncategorized (5)

Recent Posts

  • Python | The Print and Divide Puzzle October 30, 2020
  • Python | Count consecutive 1’s from a list of 0’s and 1’s October 30, 2020
  • Python | How to convert a number into a list of its digits October 26, 2020
  • Python | Validate an IP Address-IPV6(Internet Protocol version 6) October 26, 2020
  • Python | Print the first non-recurring element in a list October 26, 2020
  • Python | Print the most recurring element in a list October 26, 2020
  • Python | Find the cumulative sum of elements in a list October 26, 2020
  • Python | Check a character is present in a string or not October 26, 2020
  • Python | Check whether a string is palindrome or not October 26, 2020
  • Python | Find the missing number in the array of Ints October 26, 2020
  • Python | How would you delete duplicates in a list October 26, 2020
  • Python | Check whether an array is Monotonic or not October 26, 2020
  • Python | Check whether a number is prime or not October 26, 2020
  • Python | Print list of prime numbers up to a number October 26, 2020
  • Python | Print elements from odd positions in a list October 26, 2020
  • Python | Print positions of a string present in another string October 26, 2020
  • Python | How to sort an array in ascending order October 26, 2020
  • Python | How to reverse an array October 26, 2020
  • Python | Find un-common words from two strings October 26, 2020
  • Python | How to convert a string to a list October 26, 2020
  • Python | Find unique words from a string October 26, 2020
  • Python | Calculate average word length from a string October 26, 2020
  • Python | Find common words from two strings October 26, 2020
  • Python | Find the number of times a substring present in a string October 26, 2020
  • Python | Find maximum value from a list October 26, 2020
  • Python | How to find GCF of two numbers October 26, 2020
  • Python | How to find LCM of two numbers October 26, 2020
  • Python | How to convert a list to a string October 26, 2020
  • Python | Replace NONE by its previous NON None value October 26, 2020
  • Microsoft SQL Server 2019 | Features added to SQL Server on Linux September 26, 2018

Create a website or blog at WordPress.com

  • Follow Following
    • Improving my SQL BI Skills
    • Join 231 other followers
    • Already have a WordPress.com account? Log in now.
    • Improving my SQL BI Skills
    • Customize
    • Follow Following
    • Sign up
    • Log in
    • Report this content
    • View site in Reader
    • Manage subscriptions
    • Collapse this bar
 

Loading Comments...
 

You must be logged in to post a comment.