Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.
Random Sorting
From Wiki
Sometimes you want to display 4 random articles/pics/you name it on your web page and you don’t want to write a lot of code. SQL SERVER 2000 and up has a neat little function called NEWID() that can help you out.
First create this table and populate it
- CREATE TABLE #Test (ID INT,LastName VARCHAR(49))
- INSERT #Test VALUES(1,'Jackson')
- INSERT #Test VALUES(2,'Douglas')
- INSERT #Test VALUES(3,'Michael')
- INSERT #Test VALUES(4,'Manson')
- INSERT #Test VALUES(5,'Gabor')
- INSERT #Test VALUES(6,'Welch')
- INSERT #Test VALUES(7,'Anderson')
- INSERT #Test VALUES(8,'Vader')
Run the code below from Query Analyzer/Management Studio and keep hitting F5. You will see that the results will be different every time.
- SELECT TOP 4 *
- FROM #Test
- ORDER BY NEWID()
Contributed by: --SQLDenis 02:52, 31 May 2008 (GMT)
Part of SQL Server Programming Hacks
Section Handy tricks



LTD Social Sitings
Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.