Use of distinct in SQL

Source: Internet
Author: User
Tags sorted by name

Function: Eliminate duplicate values

One, such as:

1 Select  from T1 2 3 Select  from T1

The search results are as follows:

Distinct can be used to modify multiple columns, such as:

1 Select  from T1

Effect:

The results of the discovery are automatically sorted by the ID column, for example:

1 Select  from T1

The results of the discovery are automatically sorted by the Name column. That is, when the SELECT statement is executed, the default sorting is always made for the column to be retrieved, as in the previous example, sorted by name and then by ID.

You can sort the columns in different ways, such as:

Select  from T1 ORDER BY name Desc,id ASC

The effect is as follows:

II. Limitations

The SELECT statement in distinct can only be a field specified by distinct, and no other fields can appear, such as:

Three, and aggregation function combination

1 Select  from T1

The number of rows that will return different IDs.

But note the use of Count, the following SQL statement will be an error:

1 Select  from T1

Display error: The column ' T1.id ' in the select list is not valid because the column is not contained in an aggregate function or a GROUP by clause.

It should be written like this:

1 Select  from T1 GROUP BY ID

If there is an aggregate function in the SELECT statement, the other retrieved columns should also be included in the aggregate function or the GROUP BY clause.

For more use of the Count function, the next step is to take a separate opening.

Use of distinct in SQL

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.