How can we get the average of unique values of a column?


#1

Question

In SQL, how can we get the average of only the unique values of a column?

Answer

To run the AVG() function on a column such that it only averages the unique values in the column, we could use the DISTINCT clause right before the column name.

Example

/* Returns 2.02365 */
SELECT AVG(price)
FROM fake_apps;

/* Returns 4.15833.. */
SELECT AVG(DISTINCT price)
FROM fake_apps;