Saturday, December 2, 2023
HomePHPSQL Choose Distinct - PHPGurukul

SQL Choose Distinct – PHPGurukul


The SQL SELECT DISTINCT assertion is used to retrieve distinctive values from a specified column or set of columns in a database desk. It ensures that the outcome set incorporates solely distinct (distinctive) values, eliminating any duplicate entries. Right here’s the essential syntax for the SELECT DISTINCT assertion:

  • SELECT DISTINCT: This a part of the assertion specifies that you just wish to retrieve distinct values.
  • column1, column2, ...: These are the columns from which you wish to retrieve distinct values. You possibly can specify a number of columns.
  • FROM table_name: This a part of the assertion specifies the desk from which you wish to retrieve the information.

Right here’s an instance for example learn how to use the SELECT DISTINCT assertion:

Suppose you’ve got a desk referred to as “Workers” with the next knowledge:

EmployeeID FirstName LastName
1 John Doe
2 Jane Smith
3 John Doe
4 Mary Johnson

If you wish to retrieve an inventory of distinct first names from the “Workers” desk, you need to use the next SQL question:

The results of this question can be:

As you possibly can see, the SELECT DISTINCT assertion eradicated the duplicate “John” entry from the outcome set, returning solely distinctive first names.

You should use SELECT DISTINCT with a number of columns, relying in your necessities, to retrieve distinct combos of values from a number of columns.

In SQL, you need to use the SELECT DISTINCT assertion together with the COUNT perform to rely the variety of distinct values in a particular column or set of columns. That is helpful whenever you wish to discover the rely of distinctive values in a column. Right here’s the syntax for counting distinct values:

  • SELECT COUNT(DISTINCT column1): This a part of the assertion selects and counts the distinct values in “column1.”
  • FROM table_name: This a part of the assertion specifies the desk from which you wish to retrieve and rely the distinct values.

Right here’s an instance to exhibit learn how to use SELECT DISTINCT with COUNT:

Suppose you’ve got a desk referred to as “Orders” with the next knowledge:

OrderID CustomerName
1 John
2 Jane
3 John
4 Mary

To rely the variety of distinct buyer names within the “Orders” desk, you need to use the next SQL question:

The results of this question can be:

COUNT(DISTINCT CustomerName)
3

On this instance, the COUNT(DISTINCT CustomerName) expression counts the distinct buyer names within the “CustomerName” column, and the result’s 3, indicating that there are three distinctive buyer names within the “Orders” desk.

You can even rely distinct values in a number of columns by together with extra columns within the SELECT clause, resembling COUNT(DISTINCT column1, column2), if wanted.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments