T-SQL Challenges - Part 1 -Pivot Operator

Problematic statement:
Consider two table 1 and 2 and they are linked by a common column "ID".
Table1 had the details about the person and table2 list down the scores availed by the person.
My problem is to combine these two table listing out the person and their marks in each subjects.
In table2, the rows are added as per the subjects, first mark will be considered as subject1,
second mark will be considered as subject2,Thrid mark will be considered as subject3.
Below are the sample inputs and expected outputs,
Code Snippet

ID StudentName
1 Venkatesan
2 Arun
3 Santhi
4 Vijay

Code Snippet

ID Marks
1 90
1 20
1 80
2 78
2 67
3 89
3 65
3 98
4 78
4 76
4 45

Expected output from the above tables
Code Snippet

ID StudentName Sub1 Sub2 Sub3

1 Venkatesan 90 20 80
2 Arun 78 67 NULL
3 Santhi 89 65 98
4 Vijay 78 76 45

Microsoft sql server 2005 provides a very handy option of altering the rows to columns
using pivot property. To solve the above problem,
1. First we have to create a cte listing the rownumber partitioned by ID.
2. Pivot the data based on rownumber.
Code Snippet

--Creating table variables
declare @SQLTable1 table (id int,Studentname varchar(100))
declare @SQLTable2 table (id int,Marks int)
-- inserting the data into the table variables
insert into @SQLTable1
select '1','Venkatesan' union all
select '2','Arun' union all
select '3','Santhi' union all
select '4','Vijay'

insert into @SQLTable2
select '1','90' union all
select '1','20' union all
select '1','80' union all
select '2','78' union all
select '2','67' union all
select '3','89' union all
select '3','65' union all
select '3','98' union all
select '4','78' union all
select '4','76' union all
select '4','45'

--select * from @SQLTable1
--select * from @SQLTable2
--Creating rownumber in the cte
;with VenkatCTE as(

select a.id,a.Studentname, b.Marks,
row_number() over ( partition by a.id order by a.id) as rn
from @SQLTable1 a inner join @SQLTable2 b on a.id=b.id
--select * from VenkatCTE
-- pivoting the rows in the cte
select id,Studentname,[1] as Subject1,[2] as Subject2,[3] as Subject3
from VenkatCTE
min(Marks) for rn in ([1],[2],[3])
order by id

Happy learning!!!
Venkatesan Prabu . J


Sekhar said...

Hi Venketesan Prabhu..i am very much interested on your blog .like when ever i get a doubt on any thing related to sql server 2005 queries or any thing related i will first check ur blog....but just as my suggestion is to keep the output values screenshot also..so that it helps us a lot to knw...this is my suggestion..any how good works on sql and i want to know the extra features in sql server 2008..if u can post in ur blog it helps us a lot......

Venkatesan Prabu @ HCL said...


I have started providing the output screen.

Thanks for your positive reply

Venkatesan Prabu .J

Anonymous said...

Hi Venkat, i saw your Student sample query, I have a table where the colunmns are to be shown as columns
The table structure is:
ResId int, StatusId int, DateId int, HrId int, ResId int, price money

Data looks like
Row1: 546, 1, 8, 2, 5.00
Row2: 546, 2, 6, 3, 6.00
Row3: 546, 5, 7, 5, 12:00
Row4: 566, 1, 4, 5, 6:00
Row5: 566, 5, 6, 3, 4:00

I need data like
ResId StatusId1 DateId1 HrId1 price1 StatusId2 DateId2 HrId2 price2
and so on

546 1 8 2 5.00 2 6 3 6.00 5 7 5 12:00
566 1 4 5 6:00 5 6 3 4:00

The blanks are nulls
Status is from 1 to 5 and is a look up dimension

Any help is appreciated.



Anonymous said...

The site SQL Reports has a great SQL tutorial. Highly rcommended for people just getting started on SQL selects.

SQL Reports
URL 1: http://wwwsql-reports.net/

Sql tutorial
URL 2: http://wwwsql-reports.net/2011/03/sql-select-tutorials.html


My T-SQL Gallery @code.msdn.microsoft

Created my own T-SQL Gallery in Microsoft site. Do visit the same and share your feedback,


Thanks and Regards,
Venkatesan Prabu .J

SQL Server Interview questions - Part 1

What is the significance of NULL value and why should we avoid permitting null values?
Null means no entry has been made. It implies that the value is either unknown or undefined.We should avoid permitting null values because Column with NULL values can't have PRIMARY KEY constraints. Certain calculations can be inaccurate if NULL columns are involved.

What is SQL whats its uses and its component ?
The Structured Query Language (SQL) is foundation for all relational database systems. Most of the large-scale databases use the SQL to define all user and administrator interactions. It enable us to retrieve the data from based on our exact requirement. We will be given a flexibility to store the data in our own format.

The DML component of SQL comprises four basic statements:
* SELECT to get rows from tables
* UPDATE to update the rows of tables
* DELETE to remove rows from tables
* INSERT to add new rows to tables

What is DTS in SQL Server ?
Data Transformation Services is used to transfer the data from one source to our required destination. Considering am having some data in sql server and I need to transfer the data to Excel destination. Its highly possible with dialogue based tool called Data Transformation services. More customization can be achieved using SSIS. A specialized tool used to do such migration works.

What is the difference between SQL and Pl/Sql ?

Straight forward. SQL is a single statement to finish up our work.Considering, I need some data from a particular table. “Select * from table” will fetch the necessary information. Where as I need to do some row by row processing. In that case, we need to go for Procedural Logic / SQL.

What is the significance of NULL value and why should we avoid permitting null values?
Null means no entry has been made. It implies that the value is either unknown or undefined.We should avoid permitting null values because Column with NULL values can't have PRIMARY KEY constraints. Certain calculations can be inaccurate if NULL columns are involved.

Difference between primary key and Unique key?
Both constraints will share a common property called uniqueness. The data in the column should be unique. The basic difference is,
· Primary key won’t allow null value. Whereas, unique key will accept null value but only one null value.
· On creating primary key, it will automatically format the data inturn creates clustered index on the table. Whereas, this characteristics is not associated with unique key.
· Only one primary key can be created for the table. Any number of Unique key can be created for the table.

Select Statement in SQL Server

Select Statement in SQL Server

String Functions in sql server

String Functions in sql server

SQL Server Interview Question - Part 2

What is normalization?

Normalization is the basic concept used in designing a database. Its nothing but, an advise given to the database to have minimal repetition of data, highly structured, highly secured, easy to retrieve. In high level definition, the Process of organizing data into tables is referred to as normalization.

What is a stored procedure:
Stored procedures are precompiled T-SQL statements combined to perform a single task of several tasks. Its basically like a Macro so when you invoke the Stored procedure, you actually run a set of statements. As, its precompiled statement, execution of Stored procedure is compatatively high when compared to an ordinary T-SQL statement.

What is the difference between UNION ALL Statement and UNION ?
The main difference between UNION ALL statement and UNION is UNION All statement is much faster than UNION,the reason behind this is that because UNION ALL statement does not look for duplicate rows, but on the other hand UNION statement does look for duplicate rows, whether or not they exist.

Example for Stored Procedure?
They are three kinds of stored procedures,1.System stored procedure – Start with sp_2. User defined stored procedure – SP created by the user.3. Extended stored procedure – SP used to invoke a process in the external systems.Example for system stored proceduresp_helpdb - Database and its propertiessp_who2 – Gives details about the current user connected to your system. sp_renamedb – Enable you to rename your database

What is a trigger?

Triggers are precompiled statements similar to Stored Procedure. It will automatically invoke for a particular operation. Triggers are basically used to implement business rules.

What is a view?
If we have several tables in a db and we want to view only specific columns from specific tables we can go for views. It would also suffice the needs of security some times allowing specfic users to see only specific columns based on the permission that we can configure on the view. Views also reduce the effort that is required for writing queries to access specific columns every time.

What is an Index?
When queries are run against a db, an index on that db basically helps in the way the data is sorted to process the query for faster and data retrievals are much faster when we have an index.

What are the types of indexes available with SQL Server?

There are basically two types of indexes that we use with the SQL ServerClustered -

1. It will format the entire table, inturn physically sort the table.

2. Only one clustered index can be created for a table.

3. Data will be located in the leaf level.

4. By default, primary key will create clustered index on the table.

Non-Clustered Index

1. It wont touch the structure of the table.

2. It forms an index table as reference to the exact data.

3. A reference to the data will be located in the leaf level.

4. For a table, we can create 249 non clustered index.

Happy Learning!!!
Venkatesan Prabu .J

SQL Interview question

Extent Vs Page?

Pages are low level unit to store the exact data in sql server. Basically, the data will be stored in the mdf, ldf, ndf files. Inturn, pages are logical units available in sql server.The size of the page is 8KB.

Eight consecutive pages will form an extent 8 * 8KB = 64KB.

Thus I/O level operation will be happening at pages level.The pages will hold a template information at the start of each page (header of the page).

They are,

1. page number,

2. page type,

3. the amount of free space on the page,

4. the allocation unit ID of the object that owns the page.

Extents will be classifed into two types,

1. Uniform extents

2. Mixed extents

Uniform Extents:It occupied or used by a single object. Inturn, a single object will hold the entire 8 pages.Mixed

Extents:Mulitple objects will use the same extent. SQL Server will allow a max of eight objects to use a shared extent.

Property of SQL Server :Initally if an object is created, sql server will allocate the object to the mixed extent and once if the size reaches 8 pages and more... immediately, a new uniform extent will be provided for that particular object.

Herecomes, our fragmentation and reindexing concepts.

Best Joke - Enjoy it

Best Joke - Enjoy it