Web www.tizag.com

SQL - Distinct Usage

Distinct is used to retrieve rows of your database that have unique values for a given column. For example say we have a table of employees and in this table of employees we have several job titles from janitors to CEOs. We would like to know just how many distinct job titles we have.

SQL Code:

SELECT DISTINCT job_titles FROM employees;

Our statement will return the number of rows with a distinct value for our column (job_titles).

SQL - Distinct Multiple Columns

Using the distinct function with more than one column yields some substantial results. SQL will return the rows with distinct or unique combinations of those columns. Assume this same employee table has another column including the salary of each employee. With the use of the distinct function we can pull a list of unique job titles - salaries.

SQL Code:

SELECT DISTINCT job_titles, salary FROM employees;

SQL has returned all the rows with unique combinations of job titles and salaries. Any duplicate combinations of job titles and salaries will be ignored. For example if we had two CEOs in the table making the same salary each year, only one row would be returned but if we had two CEOs with different salaries, both rows would be returned.





New - Tizag.com Forums!
Recent Forum Topics: