ABAP Existence check of master data

  SQL

 Over View

If you want to check the existence of master data in SQL, refrain from using the COUNT command.
If you use the COUNT command, all the records will be scanned, so if the number of records is large, the performance will deteriorate.
It is better to use UP TO 1 ROWS with SELECT SINGLE or SELECT.

Sample Code:bad example

DATA: CNT TYPE I.
CLEAR: CNT.
SELECT COUNT(*) FROM MARC INTO CNT
 WHERE WERKS = 'XXXX'.
IF CNT > 0.
  WRITE: 'Found'.
ELSE.
  WRITE: 'Not Found'.
ENDIF.

Sample Code:good example1

DATA: V_MATNR type MATNR.
SELECT SINGLE MATNR INTO V_MATNR FROM MARC
 WHERE WERKS = 'XXXX'.
IF SY-SUBRC = 0.
  WRITE: 'Found'.
ELSE.
  WRITE: 'Not Found'.
ENDIF.

Sample Code:good example 2

DATA: V_MATNR type MATNR.
SELECT MATNR INTO V_MATNR FROM MARC
    UP TO 1 ROWS
 WHERE WERKS = 'XXXX'.
ENDSELECT.
IF SY-SUBRC = 0.
  WRITE: 'Found'.
ELSE.
  WRITE: 'Not Found'.
ENDIF.

Explanation

The method using the COUNT statement is described in the bad example. When the number of records is small like this
There is no particular problem with the method, but the more cases, the worse the performance.
Unless you absolutely need the number of records, you should refrain from using the COUNT statement.
Good example 1 and good example 2 described the method of acquiring only one record. If there is a existence check
If there is even one case, there is no need to count the subsequent data, so there is no problem with this method.
It is difficult to decide whether to use SELECT SINGLE or SELECT UP TO 1 ROWS
If the primary key can be used in the condition, SELECT SINGLE, otherwise, UP UP 1 ROWS of SELECT is fine.