UFO ET IT

하나의 값을 사용하는 같음 (=)과 IN 간의 성능 차이

ufoet 2021. 1. 15. 07:41
반응형

하나의 값을 사용하는 같음 (=)과 IN 간의 성능 차이


등호를 사용하고 IN 연산자가 같은 값을 가질 때 SQL 엔진은 어떻게 다릅니 까? 실행 시간이 변경됩니까?

동등성 검사 연산자를 사용한 첫 번째

WHERE column_value = 'All'

OR 연산자와 단일 값을 사용하는 두 번째

WHERE column_value IN ('All')

합니까 SQL 엔진 변화 IN=값이 하나만 있으면?

MySQL과 PostgreSQL에서 동일한 차이점이 있습니까?


이 두 문장 사이에는 차이가 없으며 옵티마이 저는를 하나의 요소 만 IN있는 =경우로 변환 IN합니다.

이와 같은 질문이있을 때 두 문을 모두 실행하고 실행 계획을 실행하고 차이점을 확인하십시오. 여기-당신은 아무것도 찾을 수 없습니다.

온라인에서 대규모 검색을 한 후이를 지원하는 SQL 문서를 찾았습니다 (모든 DBMS에 적용된다고 가정합니다).

괄호 안에 값이 하나만있는 경우이 명령은 다음과 같습니다.

WHERE "column_name"= '값 1

다음은 문서에 대한 링크 입니다.

다음은 Oracle에서 두 쿼리의 실행 계획입니다 (대부분의 DBMS에서 동일하게 처리합니다).

EXPLAIN PLAN FOR
select * from dim_employees t
where t.identity_number = '123456789'

Plan hash value: 2312174735
-----------------------------------------------------
| Id  | Operation                   | Name          |
-----------------------------------------------------
|   0 | SELECT STATEMENT            |               |
|   1 |  TABLE ACCESS BY INDEX ROWID| DIM_EMPLOYEES |
|   2 |   INDEX UNIQUE SCAN         | SYS_C0029838  |
-----------------------------------------------------

그리고 IN():

EXPLAIN PLAN FOR
select * from dim_employees t
where t.identity_number in('123456789');

Plan hash value: 2312174735
-----------------------------------------------------
| Id  | Operation                   | Name          |
-----------------------------------------------------
|   0 | SELECT STATEMENT            |               |
|   1 |  TABLE ACCESS BY INDEX ROWID| DIM_EMPLOYEES |
|   2 |   INDEX UNIQUE SCAN         | SYS_C0029838  |
-----------------------------------------------------

보시다시피 둘 다 동일합니다. 인덱싱 된 열에 있습니다. 인덱싱되지 않은 열 (전체 테이블 스캔)도 마찬가지입니다.


단일 값으로 사용하는 경우 차이가 없습니다. 위의 두 쿼리에 대해 테이블 ​​스캔, 인덱스 스캔 또는 인덱스 검색을 확인하면 두 쿼리간에 차이가 없음을 알 수 있습니다.

Mysql과 PostgresSQL에서 동일한 차이점이 있습니까?

아니요, 두 엔진에 차이가 없습니다 ( 사실 SQL Server, Oracle 등을 포함한 대부분의 데이터베이스에서 동일합니다 ). 두 엔진 모두 다음으로 변환 IN됩니다.=


실제로 큰 차이는 없지만 column_value 가 인덱싱 된 경우 IN연산자는 인덱스로 읽지 못할 수 있습니다.

이 문제가 한 번 발생 했으므로 조심하십시오.


남자에게 낚시 등을 가르치세요. 검색어의 변형이 어떤 영향을 미치는지 직접 확인하는 방법은 다음과 같습니다.

mysql> EXPLAIN SELECT * FROM sentence WHERE sentence_lang_id = "AMH"\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: sentence
         type: ref
possible_keys: sentence_lang_id
          key: sentence_lang_id
      key_len: 153
          ref: const
         rows: 442
        Extra: Using where

다른 방법으로 시도해 보겠습니다.

mysql> EXPLAIN SELECT * FROM sentence WHERE sentence_lang_id in ("AMH")\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: sentence
         type: ref
possible_keys: sentence_lang_id
          key: sentence_lang_id
      key_len: 153
          ref: const
         rows: 442
        Extra: Using where

You can read here about how to interpret the results of a mysql EXPLAIN request. For now, note that we got identical output for both queries: exactly the same "execution plan" is generated. The type row tells us that the query uses a non-unique index (a foreign key, in this case), and the ref row tells us that the query is executed by comparing a constant value against this index.


For single IN Clause,there is no difference..below is demo using an EMPS table i have..

select * from emps where empid in (1)
select * from emps where empid=1

Predicate for First Query in execution plan:

[PerformanceV3].[dbo].[Emps].[empID]=CONVERT_IMPLICIT(int,[@1],0)

Predicate for second query in execution plan:

[PerformanceV3].[dbo].[Emps].[empID]=CONVERT_IMPLICIT(int,[@1],0)

If you have multiple values in IN Clause,its better to convert them to joins


Just to add a different perspective, one of the main points of rdbms systems is that they will rewrite your query for you, and pick the best execution plan for that query and all equivalent ones. This means that as long as two queries are logically identical, the should always generate the same execution plan on a given rdbms.

That being said, many queries are equivalent (same result set) but only because of constraints the database itself is unaware of, so be careful about those cases (E.g for a flag field with numbers 1-6, the db doesn't know <3 is the same as in (1,2)). But at the end of the day, if you're just thinking about legibility of and and or statements it won't make a difference for performance which way you write them.


You will need to run execution plan on both, and see the results.

I believe they will have the same execution plan as it will be performed the same as a normal = sign when only one value is placed inside the IN() statement.

There is no reason for the optimizer to behave any differently on a query like this.

ReferenceURL : https://stackoverflow.com/questions/37828398/performance-differences-between-equal-and-in-with-one-value

반응형