Hwo to count distinct combinations of values across multiple columns in Oracle SQL

Yes  you can count distinct combinations of values across multiple columns in Oracle SQL.
However, Oracle doesn’t allow COUNT(DISTINCT col1, col2) directly (unlike some other databases).

You can achieve it using either of these three standard methods:


Method 1: Use COUNT(DISTINCT) on a concatenation (simple & common)

SELECT COUNT(DISTINCT col1 || '-' || col2) AS distinct_count
FROM your_table;

🟡 Note:

  • Use a unique separator (like '||' or CHR(1)) to avoid ambiguity (A|B vs AB|).

  • If columns can be NULL, wrap with NVL:

    SELECT COUNT(DISTINCT NVL(col1,'~') || '|' || NVL(col2,'~')) AS distinct_count
    FROM your_table;
    

Method 2: Use a subquery or GROUP BY (more robust)

SELECT COUNT(*) AS distinct_count
FROM (
  SELECT col1, col2
  FROM your_table
  GROUP BY col1, col2
);

🟢 Works perfectly for multiple columns — add as many as needed.


Method 3: Use COUNT(DISTINCT SYS_OP_COMBINED_HASH(...)) (Oracle-specific)

Efficient for large data volumes:

SELECT COUNT(DISTINCT SYS_OP_COMBINED_HASH(col1, col2))
FROM your_table;
  • This internal Oracle function computes a combined hash of multiple columns.

  • Faster than concatenation for big tables.


💡 Example:

If your table EMPLOYEES has DEPT_ID and JOB_ID:

SELECT COUNT(DISTINCT SYS_OP_COMBINED_HASH(DEPT_ID, JOB_ID)) AS unique_pairs
FROM EMPLOYEES;


Post a Comment

And that's all there is to it!

If anyone has any other questions or requests for future How To posts, you can either ask them in the comments or email me. Please don't feel shy at all!

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

Previous Post Next Post