Learning from a classic SQL query using a specified number of rows

Source: Internet
Author: User

Today, I am talking with my colleagues about an SQL command to take the specified line.

For example, if a table has 6 data records, the table now has 3 or 4 records.

Code
Declare @ table
(
Id int identity (1, 1 ),
Name varchar (10)
)

Insert into @ table
Select 'songjiang'
Union all
Select 'lin chong'
Union all
Select 'huarong'
Union all
Select 'Li yun'
Union all
Select 'lu zhishen'
Union all
Select 'wusong'

Select * from @ table

Where id in (select top 4 id from @ table) and id not in
(
Select top 2 id from @ table
)

Select top 2 * from
(
Select top 4 * from @ table order by id asc
)
Order by id desc

After performance analysis, the execution efficiency of the first method is much better than that of the second method !!!

Check the SQL analysis results.

First, the query overhead is 21%

Second, the query overhead is 57%

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.