Programing

SQL에서 count (column)과 count (*)의 차이점은 무엇입니까?

lottogame 2020. 5. 9. 09:07
반응형

SQL에서 count (column)과 count (*)의 차이점은 무엇입니까?


다음과 같은 쿼리가 있습니다.

select column_name, count(column_name)
from table
group by column_name
having count(column_name) > 1;

에 대한 모든 통화를 교체하면 어떤 차이 count(column_name)count(*)있습니까?

이 질문은 Oracle의 테이블에서 중복 값어떻게 찾습니까? .


허용 대답 (어쩌면 내 질문에) 명확히하기 위해, 교체 count(column_name)와 함께하는 count(*)이 포함 된 결과에 추가 행을 반환 null과의 수 null열의 값을.


count(*)널 (null)을 카운트 count(column)하지 않습니다

[편집] 사람들이 실행할 수 있도록이 코드를 추가했습니다.

create table #bla(id int,id2 int)
insert #bla values(null,null)
insert #bla values(1,null)
insert #bla values(null,1)
insert #bla values(1,null)
insert #bla values(null,1)
insert #bla values(1,null)
insert #bla values(null,null)

select count(*),count(id),count(id2)
from #bla

결과 7 3 2


*와 특정 열을 사용하는 것의 또 다른 사소한 차이점은 열의 경우 키워드 DISTINCT를 추가하고 개수를 다른 값으로 제한 할 수 있다는 것입니다.

select column_a, count(distinct column_b)
from table
group by column_a
having count(distinct column_b) > 1;

또 다른 미묘한 차이는 일부 데이터베이스 구현에서 실제 데이터 행이 아닌 해당 테이블의 인덱스를보고 count (*)가 계산된다는 것입니다. 특정 열이 지정되지 않았으므로 실제 열과 해당 값을 신경 쓸 필요가 없습니다 (특정 열을 계산 한 경우와 마찬가지로). 데이터베이스가 인덱스 데이터를 사용하도록 허용하면 "실제"행을 계산하는 것보다 훨씬 빠릅니다.


docs 의 설명은 이것을 설명하는 데 도움이됩니다.

COUNT (*)는 NULL 값 및 중복을 포함하여 그룹의 항목 수를 반환합니다.

COUNT (expression)은 그룹의 각 행에 대한 표현식을 평가하고 널이 아닌 값의 수를 리턴합니다.

따라서 count (*)는 null을 포함하지만 다른 방법은 null을 포함하지 않습니다.


우리는 사용할 수있는 스택 Exchange 데이터 탐색기를 간단한 쿼리와의 차이를 설명하기 위해. Stack Overflow 데이터베이스의 Users 테이블에는 사용자의 웹 사이트 URL과 같이 비어있는 열이 있습니다.

-- count(column_name) vs. count(*)
-- Illustrates the difference between counting a column
-- that can hold null values, a  'not null' column, and  count(*)

select count(WebsiteUrl), count(Id), count(*) from Users

당신이에 위의 쿼리를 실행하면 데이터 탐색기를 , 당신은 개수가 동일하다고 볼 수 있습니다 count(Id)count(*)때문에 Id열 수 없습니다 null값을. WebsiteUrl그 열 수 있기 때문에 카운트는하지만, 훨씬 낮다 null.


Basically the COUNT(*) function return all the rows from a table whereas COUNT(COLUMN_NAME) does not; that is it excludes null values which everyone here have also answered here. But the most interesting part is to make queries and database optimized it is better to use COUNT(*) unless doing multiple counts or a complex query rather than COUNT(COLUMN_NAME). Otherwise, it will really lower your DB performance while dealing with a huge number of data.


  • The COUNT(*) sentence indicates SQL Server to return all the rows from a table, including NULLs.
  • COUNT(column_name) just retrieves the rows having a non-null value on the rows.

Please see following code for test executions SQL Server 2008:

-- Variable table
DECLARE @Table TABLE
(
      CustomerId int NULL 
    , Name nvarchar(50) NULL
)

-- Insert some records for tests
INSERT INTO @Table VALUES( NULL, 'Pedro')
INSERT INTO @Table VALUES( 1, 'Juan')
INSERT INTO @Table VALUES( 2, 'Pablo')
INSERT INTO @Table VALUES( 3, 'Marcelo')
INSERT INTO @Table VALUES( NULL, 'Leonardo')
INSERT INTO @Table VALUES( 4, 'Ignacio')

-- Get all the collumns by indicating *
SELECT  COUNT(*) AS 'AllRowsCount'
FROM    @Table

-- Get only content columns ( exluce NULLs )
SELECT  COUNT(CustomerId) AS 'OnlyNotNullCounts'
FROM    @Table

COUNT(*) – Returns the total number of records in a table (Including NULL valued records).

COUNT(Column Name) – Returns the total number of Non-NULL records. It means that, it ignores counting NULL valued records in that particular column.


It is best to use

Count(1) in place of column name or * 

to count the number of rows in a table, it is faster than any format because it never go to check the column name into table exists or not


There is no difference if one column is fix in your table, if you want to use more than one column than you have to specify that how much columns you required to count......

Thanks,


As mentioned in the previous answers, Count(*) counts even the NULL columns, whereas count(Columnname) counts only if the column has values.

It's always best practice to avoid * (Select *, count *, …)

참고URL : https://stackoverflow.com/questions/59294/in-sql-whats-the-difference-between-countcolumn-and-count

반응형