Why the order by cannot be used directly in the Union clause

Source: Internet
Author: User
Tags definition table definition

Today a group of brothers asked a question, said there is a table, there are a lot of data in the table, which has a field type, you want to randomly remove 10 records from the table, including 5 type=1 another 5 type=0, such as the following image:

I think, this is not simple, according to the requirements, each take top 5, since it is random take, then the order by NEWID () is three, and then all the data union up. So I immediately gave the answer:

select top 5 * from xxx where type=1 order by newid()
union
select top 5 * from xxx where type=0 order by newid()

But the brother said wrong, grammar is wrong, I at first glance, seems to have no problems, so let him give me the definition of the table, I try on this machine, the table definition is:

CREATE TABLE [dbo]. [Question] (
[ID] [int] IDENTITY (1,1) not NULL,
[Question] [varchar] () not NULL,
[Answer] [varchar] () not NULL,
[Type] [Bit] Not NULL,
CONSTRAINT [pk_question] PRIMARY KEY CLUSTERED
(
[ID] ASC
With (pad_index = off, statistics_norecompute = off, Ignore_dup_key = off, allow_row_locks = ON, allow_page _locks = on) on [PRIMARY]
) on [PRIMARY]

So my statement into the SSMS, the result system is really an error: Incorrect syntax near the keyword ' order '.

What's going on? It doesn't look like a problem. So I do it alone.

select top 5 * from dbo.Question
where [type]=1
ORDER BY newid()

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.