programing

오라클에서 행이 있는지 확인하는 가장 빠른 쿼리?

lovejava 2023. 8. 22. 21:41

오라클에서 행이 있는지 확인하는 가장 빠른 쿼리?

저는 오라클을 사용하고 있고, 매우 큰 테이블을 가지고 있습니다.간단한 기준에 맞는 행이 있는지 확인해야 합니다.간단한 SQL을 사용하여 이 문제를 해결하는 가장 좋은 방법은 무엇입니까?

다음은 제가 예상하는 바와 같이, 제 목적에 충분히 빠르지만 기본적으로 Oracle에서 SQL Server의 "존재"를 수행하는 표준적인 방법을 배우고 싶습니다.

select count(x_id) from x where x.col_a = value_a and x.col_b = value_b;

그러면 카운트()가 다른 계층에서 부울로 반환됩니다.요점은 Oracle이 이 쿼리에 대해 최소화를 수행하기를 원한다는 것입니다. 조건과 일치하는 행이 있는지만 알면 됩니다.

네, 그 열들은 분명히 색인화될 것입니다.

rownum=1을 사용하는 경우 COUNT(*)를 사용해도 됩니다.

declare
   l_cnt integer;
begin
   select count(*)
   into   l_cnt
   from   x
   where  x.col_a = value_a 
   and    x.col_b = value_b
   and    rownum = 1;
end;

그러면 항상 행이 반환되므로 NO_DA를 처리할 필요가 없습니다.TA_FAWN 예외입니다.l_cnt 값은 0(행 없음) 또는 1(행이 하나 이상 있음)입니다.

Rownum을 사용하여 카운트 쿼리를 최적화하는 것보다 EXISTS를 사용하는 것이 질문에 대한 더 자연스러운 답변을 제공한다고 생각합니다.

Oracle이 ROWNUM 최적화를 지원합니다.

create or replace function is_exists (
        p_value_a varchar2,
        p_value_b varchar2)
        return boolean
is

   v_exists varchar2(1 char);

begin

    begin
        select 'Y' into v_exists from dual
        where exists
            (select 1 from x where x.col_a = p_value_a and x.col_b = p_value_a);

    exception

        when no_data_found then

            v_exists := null;

    end;

    return v_exists is not null;

end is_exists;
SELECT  NULL
FROM    x
WHERE   x.col_a = value_a
        AND x.col_b = value_b
        AND rownum = 1

COUNT(*)모든 행을 셀 필요가 있기 때문에 확실히 최선의 방법은 아닙니다, 반면에.ROWNUM = 1첫 번째 일치하는 행을 찾는 즉시 반환합니다.

여기 있습니다.PL/SQL코드:

DECLARE
        ex INT;
BEGIN
        BEGIN
                SELECT  NULL
                INTO    ex
                FROM    dual
                WHERE   1 = 1
                        AND rownum = 1;
                DBMS_OUTPUT.put_line('found');
        EXCEPTION
        WHEN no_data_found THEN
                DBMS_OUTPUT.put_line('not found');
        END;
END;
begin
select 'row DOES exist' 
  into ls_result
from dual
where exists (select null from x where x.col_a = value_a and x.col_b = value_b);
exception
when no_data_found then
  ls_result := ' row does NOT exist';
end;

언급URL : https://stackoverflow.com/questions/1088156/quickest-query-to-check-for-the-existence-of-a-row-in-oracle