Search code examples
oracle-databaseplsql

PL/SQL function return all rows from the table when it should return a specific row


I have the following plsql function and the problem it has is that it returns all the rows of the table, and the condition is very clear CODE = code. Why could this be happening?

FUNCTION GET_UNIT_BY_PK (code IN VARCHAR2)
RETURN CLOB
IS
    l_result CLOB;
BEGIN
    SELECT '[' || 
           '{ "CODE": "' || CODE || '", "TITLE": "' || TITLE || '", "SUBTITLE": "' || SUBTITLE || '", "DESCRIPTION": "' || DESCRIPTION || '", "KEYWORDS": "' || KEYWORDS || '", "STATUS": "' || STATUS || '" }' || 
           ']'
    INTO l_result
    FROM F_UNITS
    WHERE CODE = code;

    RETURN l_result;
END;

If I limit the number of rows with ROWNUM = 1, it returns the first row of the table. Why is this?

FUNCTION GET_UNIT_BY_PK (code IN VARCHAR2)
RETURN CLOB
IS
    l_result CLOB;
BEGIN
    SELECT '[' || 
           '{ "CODE": "' || CODE || '", "TITLE": "' || TITLE || '", "SUBTITLE": "' || SUBTITLE || '", "DESCRIPTION": "' || DESCRIPTION || '", "KEYWORDS": "' || KEYWORDS || '", "STATUS": "' || STATUS || '" }' || 
           ']'
    INTO l_result
    FROM F_UNITS
    WHERE CODE = code AND ROWNUM=1;

    RETURN l_result;
END;

Solution

  • You are comparing a column to itself (remember that both SQL and PL/SQL are case-insensitive, so CODE and code are the same). It isn't even looking at your parameter. It's comparing the code column to itself, which will match all rows. You need to name your parameter/variable something different than the column name to prevent this.