Free Newsletters:
DatabaseJournal  
DBANews
Search Database Journal:
 
HOME News MS SQL Oracle DB2 Access MySQL PostgreSQL PHP SQL Etc Scripts Links Discussion
internet.com

» HOME
» NEWS
» FEATURES
» SERIES
MS SQL
Oracle
MS Access
MySQL
DB2
» RESOURCES
Products
Scripts
Links
» DISCUSSION
» TECH JOBS

Marketplace Partners
Be a Marketplace Partner




internet.commerce
Be a Commerce Partner
Corporate Gifts
Laptop Batteries
Shop
Promote Your Website
Corporate Awards
Computer Hardware
Prepaid Phone Card
Imprinted Promotions
Server Racks
PDA Phones & Cases
Dental Insurance
GPS Devices
Online Education
Auto Insurance Quote




MySpace Joins eBay, Yahoo in Open Profile Push

News Corp. Unit Under Fire for Ties to Hacker

Are Non-PC Devices Hurting 'Net Innovation?

internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers


Linked Data Planet Conference & Expo

CA ERwin® Data Modeler Proven database design and modeling. Efficiently analyze, design and deploy effective database solutions. Whitepaper: Manage SQL Server Deployments
Try it free: CA ERwin® Data Modeler

Access FREE IPSWITCH Networking Tools:
Access FREE IPSWITCH Networking Tools:
Download:
WhatsUp Gold Premium Edition v12
Comprehensive single-site network and application management installs, discovers, and maps network assets in minutes.

Download:
WhatsUp Gold Distributed Edition v12 - Central Site
This powerful network management and application monitoring solution is designed expressly for large enterprise organizations with complex multi-site networks. Reducing management complexity, the solution offers NOC-based views into infrastructure and applications.

Download:
WhatsUp Gold Distributed Edition v12 - Remote Site


Solaris 8 Migration Assistant
Rapidly move your Solaris 8 application environments to new systems running Solaris 10 with the Solaris 8 Migration Assistant. Reduce migration risk while taking advantage of increased performance, reliability and security of the latest SPARC hardware platforms and Solaris 10 OS. »

 
Sun Eco Innovation: Good for Business, Good for the Environment
A complete solution to help you optimize and refresh your datacenter while properly recycling equipment and eliminating eWaste, including money-saving promotions to lower hardware acquisition costs. »

 
Sun Eco Innovation: Power Calculators
Power consumption has increasingly become a priority in customer's minds when purchasing new systems or storage. Sun's Power Calculators provide data on power consumption of Sun products allowing IT managers to better plan the power requirements in the datacenter to achieve better energy and cost savings. »

 
Optimize the Web Tier: Consolidate to Get More Performance in Less Space and Lower Power Consumption
Expansion in the Web tier is generally accomplished by adding more servers whenever extra capacity is needed. As the pool of servers grows larger, however, the complexity of the environment can grow exponentially. »

Production Manager (hands on)
Aquent
US-MA-Cambridge

Justtechjobs.com Post A Job | Post A Resume
MS SQL
September 7, 2005
"TOP" Clause in SQL Server 2005
By Muthusamy Anantha Kumar aka The MAK

We all know the "TOP" clause returns the first n number of rows or percentage of rows thereby limiting the number of resulting rows displayed when we are selecting rows in a table.

SQL Server 2005 is packed with new features and enhancements. One of the enhancements in SQL 2005 that we are going to see is the clause, "TOP." The "TOP" clause will now allow us to do Data Manipulation and also allow similar criteria results to be displayed by using the TIES option.

Let us create a table and insert a bunch of rows. Execute the query below to create the table "MyTable2" and insert a few rows.

 
Create table Mytable2 (au_id int, 
 authors_name varchar(100))
Go
insert into MyTable2 select 110,'Mathew Arnold'
insert into MyTable2 select 140,'Keith Davis'
insert into MyTable2 select 76,'David Taylor'
insert into MyTable2 select 127,'Agatha Christy'
insert into MyTable2 select 12,'Sidney Sheldon'
insert into MyTable2 select 12,'Mcarthur'
insert into MyTable2 select 76,'Alan Smiles'
insert into MyTable2 select 100,'Kreisler'
insert into MyTable2 select 88,'Jeff Watch'
insert into MyTable2 select 99,'William Anderson'
insert into MyTable2 select 99,'William Anderson'
go

Let us query the entire table. Execute the query below to display the entire table.

Select * from MyTable2

Here is the result set.

au_id

AuthorsName

110

Mathew Arnold

140

Keith Davis

76

David Taylor

127

Agatha Christy

12

Sidney Sheldon

12

Mcarthur

76

Alan Smiles

100

Kreisler

88

Jeff Watch

99

William Anderson

99

William Anderson

Now let us query only the top 5 rows using the following query.

Select top 5 * from MyTable2

Here is the result set.

au_id

authors_name

110

Mathew Arnold

140

Keith Davis

76

David Taylor

127

Agatha Christy

12

Sidney Sheldon

The same results can be produced using the set rowcount statement.

set rowcount 5
select * from MyTable2
set rowcount 0

Here is the result set.

au_id

authors_name

110

Mathew Arnold

140

Keith Davis

76

David Taylor

127

Agatha Christy

12

Sidney Sheldon

In SQL 2005, the delete and update operations can also be performed using the TOP clause. Let us execute the following query to update the authors name in the first two rows of the table with the suffix 'Mr.'

Update top (2) MyTable2 set authors_name = 'Mr. ' + authors_name
select * from MyTable2

The query result will return all of the rows from the table after updating the top two rows. Notice the the top two rows have been updated with the suffix 'Mr.'

Here is the result set.

au_id

authors_name

110

Mr. Mathew Arnold

140

Mr. Keith Davis

76

David Taylor

127

Agatha Christy

12

Sidney Sheldon

12

Mcarthur

76

Alan Smiles

100

Kreisler

88

Jeff Watch

99

William Anderson

99

William Anderson

The same results can be produced using the set rowcount.

Set rowcount 3
Update  MyTable2 set authors_name = 'Mr. ' + authors_name
set rowcount 0
select * from MyTable2

Here is the result set.

au_id

authors_name

110

Mr. Mr. Mathew Arnold

140

Mr. Mr. Keith Davis

76

Mr. David Taylor

127

Agatha Christy

12

Sidney Sheldon

12

Mcarthur

76

Alan Smiles

100

Kreisler

88

Jeff Watch

99

William Anderson

99

William Anderson

Let us do a delete operation on the table using the TOP clause.

delete top (1) MyTable2 where left(authors_name,2)= 'Mr'
select * from MyTable2

Here is the result set.

au_id

authors_name

140

Mr. Mr. Keith Davis

76

Mr. David Taylor

127

Agatha Christy

12

Sidney Sheldon

12

Mcarthur

76

Alan Smiles

100

Kreisler

88

Jeff Watch

99

William Anderson

99

William Anderson

The same results can be produced using the set rowcount.

set rowcount 1
delete MyTable2 where left(authors_name,2)= 'Mr'
set rowcount 0
select * from MyTable2

Here is the result set.

au_id

authors_name

76

Mr. David Taylor

127

Agatha Christy

12

Sidney Sheldon

12

Mcarthur

76

Alan Smiles

100

Kreisler

88

Jeff Watch

99

William Anderson

99

William Anderson

Another additional feature of the TOP clause is the number specified after the clause TOP can be substituted by a variable. Using this feature it is easy to change the number of limiting rows on the fly.

Example:

declare @n int
set @n=3
select top (@n) *  from MyTable2

Here is the result set.

au_id

authors_name

76

Mr. David Taylor

127

Agatha Christy

12

Sidney Sheldon

The TOP clause also comes with another feauture called TIES. If you would like to include similar criteria together when using TOP clause, then TIES can be used.

For example the following query returns the TOP 10 % of the table.

select top 10 percent
*
from mytable2 order by au_id

Here is the result set.

au_id

authors_name

12

Sidney Sheldon

But we know that there is another row with the same au_id values.

Now let us include the TIES option in the query.

select top 10 percent with ties
*
from mytable2 order by au_id

Here is the result set.

au_id

authors_name

12

Sidney Sheldon

12

Mcarthur

Conclusion

This article has illustrated the new enhancements of the TOP clause in SQL 2005.

» See All Articles by Columnist MAK

Tools:
Add databasejournal.com to your favorites
Add databasejournal.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed

MS SQL Archives

Download: Solaris 8 Migration Assistant. Run Solaris 8 apps on the latest SPARC systems and Solaris 10.
Five Trends for Application Development. Download Your Complimentary Report. Exclusive. Act Now.
HP eBook: Using Business Service Management (BSM) to Manage Your Business Applications
Flash Demo: Learn how IBM Information Server Blade is easy to manage, highly scalable and efficient.
What's The Future Of IT? Find Out By Reading "IT in 2018" Now. Free Registration Required.


Latest Forum Threads
MS SQL Forum
Topic By Replies Updated
How To Transfer Access Data Records To SQL ?? ankurdjariwala 1 May 8th, 12:24 PM
problem with federated server linking majidkhan 1 April 29th, 10:00 AM
"SELECT rowguidcol" from tables on linked servers? brentbordelon 1 April 25th, 04:12 PM
"SELECT rowguidcol" vs. "SELECT <actual name>" rgarrison 9 April 16th, 03:46 PM







JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES