#BESTWORSTCODE

Last month, on April 24th, Redgate hosted the #BESTWORSTCODE contest. Unfortunately, I wasn’t able to participate at the time. Better late than never, I suppose.

Erik Darling blogged about his example recently. This gave me an idea of something really dumb I could do.

PIVOT/UNPIVOT

Moving Ross Geller GIF - Find & Share on GIPHY

You might be able to take a guess at where this is going. Let’s PIVOT and UNPIVOT to make things go wrong. On purpose.

I’m not working with the pubs database (as the challenge specified), but I’m sure this concept could also be applied in a similar fashion. I’ll be working with the “Users” table in the StackOverflow database.

USE StackOverflow2013;
GO

WITH CTE
AS
(
SELECT Id,       
	   DownVotes,	  
	   UpVotes	   
FROM dbo.Users
)
SELECT *
FROM CTE
    UNPIVOT
    (
        VALUE FOR COL IN (DownVotes, UpVotes)
    ) AS UnPvt
	PIVOT
    (
        SUM(VALUE) FOR COL IN (DownVotes, UpVotes)
    ) AS Pvt;

You may notice these results are identical to the returned rows inside that CTE. We’re rotating these results around multiple times for absolutely no reason, other than to slow things down.

But… why?

Working with bad code can teach us to write code in a more efficient manner. There are lots of things we can do to make this run worse. I’d love to see what “bad code” you can come up with!

Thanks for reading!

Leave a Reply

Your email address will not be published. Required fields are marked *