JIYIK CN >

Current Location:Home > Learning > DATABASE > PostgreSQL >

PostgreSQL distinct field value count

Author:JIYIK Last Updated:2025/04/09 Views:

Getting the distinct values ​​in a field is an important query. This article discusses how to get the distinct count of values ​​in a field.

Get distinct count of field values ​​in PostgreSQL

Consider a quiz_scoretable that records the score of each participant in a quiz game.

id player_id score
1 1 10
2 2 10
3 3 18
4 4 69
5 5 24
6 6 67
7 7 94
8 8 68
9 9 33
10 10 5

Here is the table CREATEstatement:

CREATE TABLE quiz_score
(
    id integer NOT NULL GENERATED ALWAYS AS IDENTITY,
    player_id integer NOT NULL,
    score integer NOT NULL,
    CONSTRAINT quiz_score_pkey PRIMARY KEY (id)
);

Here is INSERTthe statement that populates the table with data:

INSERT INTO quiz_score (player_id, score)
SELECT i, floor(random()*(100-0+1))
FROM generate_series(1,10000000) i;

We have inserted 10 million random scores into our table. Let's find out how many different scores there are in the table by running the following query:

SELECT COUNT(DISTINCT score) FROM quiz_score;

This query took 3 seconds 391 milliseconds and counted 101 distinct values.

We can also run this other query to find the number of distinct scores in the table:

SELECT COUNT(*) FROM (SELECT DISTINCT score FROM quiz_score) AS DistinctScores;

This new query took 1 second and 572 milliseconds and counted 101 distinct values.

As we can see, the second query is faster. Either query would work fine, but in this case, the second query is faster.

Get distinct count of field values ​​based on another field in PostgreSQL

We will now introduce a Expertisenew column called . This field is populated based on the player's score.

ExpertiseThe values ​​are: Beginner, Intermediary, Expertand Master. A player's expertise is determined by the player's score as follows:

Expertise score
Beginner 0 - 50
Intermediary 51 - 80
Expert 81 - 90
Master 91 - 100

The newly updated quiz_scoretables are:

id player_id score player_rank
1 1 10 Beginner
2 2 10 Beginner
3 3 18 Beginner
4 4 69 Intermediary
5 5 24 Beginner
6 6 67 Intermediary
7 7 94 Master
8 8 68 Intermediary
9 9 33 Beginner
34 34 89 Expert

This is the statement used to add a new column to a table ALTER TABLE:

ALTER TABLE quiz_score ADD COLUMN expertise text;

Here is the statement that populates the expertise field UPDATE:

UPDATE quiz_score
SET expertise =
(CASE
    WHEN score >= 0
        AND score <= 50 THEN 'Beginner'
    WHEN score > 50
        AND score <= 80 THEN 'Intermediary'
    WHEN score > 80
        AND score <= 90 THEN 'Expert'
    WHEN score > 90 THEN 'Master'
END);

In the previous example, we looked at the different scores in the table. In this example, let's find out how many different scores there are for each expertise in the table by running the following query:

SELECT expertise, COUNT(DISTINCT score)
FROM quiz_score
GROUP BY expertise

The results are as follows:

  expertise   | count
--------------+-------
 Beginner     |    51
 Intermediary |    10
 Expert       |    30
 Master       |    10

From this query, we can see Beginnerthat major has 51 different scores, Intermediaryhas 10 different scores, Experthas 30 different scores, and Masterhas 10 different scores. The query took 14 seconds and 515 milliseconds.

We can also run this other query to find the number of distinct scores in the table:

SELECT
    DISTINCT ON (expertise) expertise,
    COUNT(DISTINCT score)
FROM
    quiz_score
GROUP BY expertise

This new query took 12 seconds and 165 milliseconds. In the second example, the second query is faster, but either query will work fine.

In this article, we discussed how to get distinct values ​​in a field and how to get distinct values ​​in a field based on distinct values ​​of another field.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Terminate the PostgreSQL connection

Publish Date:2025/04/11 Views:199 Category:PostgreSQL

In this article, we will learn how to terminate a PostgreSQL session. Any open connections are run by background processes or tasks, PSQL which may no longer exist despite exiting the user interface or command line tool. Use ps -ef or grep

Single query to rename and change column type in PostgreSQL

Publish Date:2025/04/11 Views:166 Category:PostgreSQL

This article describes how to rename a column and change its type in PostgreSQL using only a single query. Renaming and changing column types in MySQL In MySQL , if you want to change the column type and rename it, you can use a simple stat

Joining columns using Select in PostgreSQL

Publish Date:2025/04/11 Views:176 Category:PostgreSQL

MySQL PostgreSQL is an object-relational database system, which means it can support more complex data types than its competitors . Today we will learn how to use SELECT the operator to join the columns of a table. Using operators to || joi

Using CASE in PostgreSQL

Publish Date:2025/04/11 Views:124 Category:PostgreSQL

This article shows how to use the statement in PostgreSQL CASE . CASE How to use the statement in PostgreSQL case Statements are similar to those in general-purpose programming languages if-else . But in SQL, if you want to write IF-ELSE ,

Using NOT IN with subqueries in PostgreSQL

Publish Date:2025/04/11 Views:93 Category:PostgreSQL

NOT IN The inverts the result of NOT simply using IN the operator. NOT IN The right side of the operator must have a subquery in which multiple columns are returned to check whether the expression matches the data. NOT IN Tends to return tr

Using variables in PostgreSQL

Publish Date:2025/04/11 Views:171 Category:PostgreSQL

This article will demonstrate how we can declare and assign values ​​to variables in PostgreSQL. In PostgreSQL, DECLARE variables are declared using Often you will need variables in your PL/SQL scripts. In DECLARE the section called , y

Connect to PostgreSQL using a password

Publish Date:2025/04/11 Views:171 Category:PostgreSQL

This article shows various ways to connect to PostgreSQL using a password. It can be through the command line, pgpass a file, PGPASSWORD an environment variable or a connection string. Connecting to PostgreSQL with a password using the comm

Deleting a database in PostgreSQL via PSQL

Publish Date:2025/04/11 Views:166 Category:PostgreSQL

There are two ways to access PostgreSQL objects and databases on your system. One is through an interface, such as a graphical interface like PGADMIN, and the other is the basic command line tool psql. Today, we will look at DROP DATABASE t

Using the database in PostgreSQL

Publish Date:2025/04/11 Views:132 Category:PostgreSQL

This article demonstrates connecting to a database, creating a new database, and creating a table in PostgreSQL. Available databases in PostgreSQL You can run the following command after opening the Postgres command line to view all availab

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial