오라클 COUNT where - olakeul COUNT where

COUNT( ) 함수는 오라클에서 아주 기본적인 함수이며 자주 사용한다. 그러나 전체 건수를 반환하는 COUNT(*) 외에 다양한 사용방법이 있으니 아래를 참고하여 활용하면 좋을 것 같다.

COUNT( ) 함수 사용법

SELECT COUNT(*)            cnt 
     , COUNT(mgr)          cnt2 
     , COUNT(DISTINCT job) cnt3 
  FROM emp

오라클 COUNT where - olakeul COUNT where

COUNT(*)

  - 조회된 전체행 건수를 반환한다

COUNT(컬럼)

  - 컬럼의 값이 NULL인 행은 카운트 하지 않는다

COUNT(DISTINCT 컬럼)

  - 컬럼 값을 중복제거하고, 컬럼의 값 건수를 반환한다

GROUP BY ~ HAVING

오라클 COUNT where - olakeul COUNT where

- COUNT( ) 함수는 집계 함수이기 때문에 GROUP BY 절과 함께 사용할 수 있다

- WHERE 절에는 COUNT( ) 함수를 사용할 수 없지만, HAVING 절에는 조건으로 사용 가능하다.

함수사용

오라클 COUNT where - olakeul COUNT where

- COUNT( ) 함수 내부에 DECODE 함수나 CASE문 등을 사용하여 건수를 집계 할 수 있다.

COUNT(*) vs COUNT(1) 성능비교

COUNT(*)은 모든 컬럼 지칭하는 아스타리스크(*)가 있어 성능에 영향을 미칠 것으로 생각되어 COUNT(1)로 사용하는 경우가 있다. 그러나 위 두 가지의 경우 성능은 차이가 없기 때문에 일반적인 COUNT(*)을 사용하는 것을 권장한다.

COUNT_예제_쿼리(테이블포함).txt

0.01MB

I have a table like this:

+-----+-----+-------+
| id  | fk  | value |
+-----+-----+-------+
| 0   | 1   | peter |
| 1   | 1   | josh  |
| 3   | 2   | marc  |
| ... | ... | ...   |

I'd like now to get all entries which have more than one value. The expected result would be:

+-----+-------+
| fk  | count |
+-----+-------+
| 1   | 2     |
| ... | ...   |

I tried to achieve that like this:

select fk, count(value) from table where count(value) > 1;

But Oracle didn't like it.

So I tried this...

select * from (
    select fk, count(value) as cnt from table
) where cnt > 1;

...with no success.

Any ideas?

Summary: in this tutorial, you will learn how to use the Oracle COUNT() function to get the number of items in a group.

The Oracle COUNT() function is an aggregate function that returns the number of items in a group.

The syntax of the COUNT() function is as follows:

COUNT( [ALL | DISTINCT | * ] expression)

Code language: SQL (Structured Query Language) (sql)

The COUNT() function accepts a clause which can be either ALL, DISTINCT, or *:

  • COUNT(*) function returns the number of items in a group, including NULL and duplicate values.
  • COUNT(DISTINCT expression) function returns the number of unique and non-null items in a group.
  • COUNT(ALL expression) evaluates the expression and returns the number of non-null items in a group, including duplicate values.

If you don’t explicitly specify DISTINCT or ALL, the COUNT() function uses the ALL by default.

Note that, unlike other aggregate functions such as AVG() and SUM(), the COUNT(*) function does not ignore NULL values.

Oracle COUNT() examples

Let’s take some examples of using the COUNT() function.

A) COUNT(*) vs. COUNT(DISTINCT expr) vs. COUNT(ALL)

Let’s create a table named items that consists of a val column and insert some sample data into the table for the demonstration.

CREATE TABLE items(val number); INSERT INTO items(val) VALUES(1); INSERT INTO items(val) VALUES(1); INSERT INTO items(val) VALUES(2); INSERT INTO items(val) VALUES(3); INSERT INTO items(val) VALUES(NULL); INSERT INTO items(val) VALUES(4); INSERT INTO items(val) VALUES(NULL); SELECT * FROM items;

Code language: SQL (Structured Query Language) (sql)
오라클 COUNT where - olakeul COUNT where

The following statement uses the COUNT(*) function to return the number of rows in the items table including NULL and duplicate values:

SELECT COUNT(*) FROM items;

Code language: SQL (Structured Query Language) (sql)
오라클 COUNT where - olakeul COUNT where

The following statement uses the COUNT(DISTINCT val) to return only the number of distinct and non-null rows from the items table:

SELECT COUNT( DISTINCT val ) FROM items;

Code language: SQL (Structured Query Language) (sql)
오라클 COUNT where - olakeul COUNT where

The following statement uses the COUNT(ALL val) function to return the number of non-null rows in the items table, considering duplicates.

SELECT COUNT( ALL val ) FROM items;

Code language: SQL (Structured Query Language) (sql)
오라클 COUNT where - olakeul COUNT where

B) Simple Oracle COUNT() example

The following example returns the number of rows in the products table:

SELECT COUNT(*) FROM products;

Code language: SQL (Structured Query Language) (sql)
오라클 COUNT where - olakeul COUNT where

C) Oracle COUNT() with WHERE clause example

If you want to find the number of products in the category id 1, you can add a WHERE clause to the query above:

SELECT COUNT(*) FROM products WHERE category_id = 1;

Code language: SQL (Structured Query Language) (sql)
오라클 COUNT where - olakeul COUNT where

D) Oracle COUNT() with GROUP BY clause example

To find the number of products in each product category, you use the following statement:

SELECT category_id, COUNT(*) FROM products GROUP BY category_id ORDER BY category_id;

Code language: SQL (Structured Query Language) (sql)
오라클 COUNT where - olakeul COUNT where

In this example,

  • First, the GROUP BY clause divides the products into groups based on the product category (category_id).
  • Second, the COUNT(*) function returns the number of products for each group.

E) Oracle COUNT() with LEFT JOIN clause

The following examples get all category names and the number of products in each category by joining the product_categories with the products table and using the COUNT() function with the GROUP BY clause.

SELECT category_name, COUNT( product_id ) FROM product_categories LEFT JOIN products USING(category_id) GROUP BY category_name ORDER BY category_name;

Code language: SQL (Structured Query Language) (sql)
오라클 COUNT where - olakeul COUNT where

F) Oracle COUNT() with HAVING clause example

The following statement retrieves category names and the number of products in each. In addition, it uses a HAVING clause to return the only category whose the number of products is greater than 50.

SELECT category_name, COUNT( product_id ) FROM product_categories LEFT JOIN products USING(category_id) GROUP BY category_name HAVING COUNT( product_id ) > 50 ORDER BY category_name;

Code language: SQL (Structured Query Language) (sql)
오라클 COUNT where - olakeul COUNT where

G) Using Oracle COUNT() and HAVING clause to find duplicate values

You can use the COUNT() function and a HAVING clause to find rows with duplicate values in a specified column.

For example, the following statement returns the contacts’ last names that appear more than one:

SELECT last_name, COUNT( last_name ) FROM contacts GROUP BY last_name HAVING COUNT( last_name )> 1 ORDER BY last_name;

Code language: SQL (Structured Query Language) (sql)
오라클 COUNT where - olakeul COUNT where

In this statement:

  • Firstly, the GROUP BY clause divides the rows in the contacts table into groups based on the values in the last_name column.
  • Secondly, the COUNT() function returns the number of the same last names for each last name.
  • Finally, the HAVING clause returns only groups that have more than one value of the last name.

In this tutorial, you have learned how to use the Oracle COUNT() function to return the number of items in a group.

Was this tutorial helpful?