LIKE, NOT LIKE

LIKE operator searches a string for a pattern. The patterns can have the following two wildcard characters:

ItemDescription
Underscore (_)Matches one character in a specified position
Percent (%)Matches any number of characters

For example, '_A%' matches any one character in the first position, the A matches an A character in the second position, and the percent (%) matches any characters following the A character.


CREATE TABLE EMP (EMPNO NUMBER(4) NOT NULL,
                      ENAME VARCHAR2(10),
                      HIREDATE DATE);

INSERT INTO EMP VALUES (1, 'SMITH', TO_DATE('17-DEC-1980', 'DD-MON-YYYY'));
INSERT INTO EMP VALUES (2, 'ALLEN', TO_DATE('20-FEB-1981', 'DD-MON-YYYY'));
INSERT INTO EMP VALUES (3, 'WARD',  TO_DATE('22-FEB-1981', 'DD-MON-YYYY'));
INSERT INTO EMP VALUES (4, 'JONES', TO_DATE('2-APR-1981',  'DD-MON-YYYY'));
INSERT INTO EMP VALUES (5, 'MARTIN',TO_DATE('28-SEP-1981', 'DD-MON-YYYY'));

SQL> select * from emp where ename like '_A%';

     EMPNO ENAME      HIREDATE
---------- ---------- ---------
         3 WARD       22-FEB-81
         5 MARTIN     28-SEP-81

SQL>

Using NOT LIKE:

SQL> select * from emp where ename not like '_A%';

     EMPNO ENAME      HIREDATE
---------- ---------- ---------
         1 SMITH      17-DEC-80
         2 ALLEN      20-FEB-81
         4 JONES      02-APR-81

SQL>

To search for actual underscore or percent characters in a string, use the ESCAPE option.

For example, '%\%%' ESCAPE '\'

The character after the ESCAPE specifies the character used for escaping. In the example the backslash character (\) is used as the 'escape character'. The first % is treated as a wildcard. The second % is treated as an actual character to search for. The third % is treated as a wildcard.


CREATE TABLE EMP (EMPNO    NUMBER(4) NOT NULL,
                  ENAME    VARCHAR2(10),
                  HIREDATE DATE);

INSERT INTO EMP VALUES (1, 'S%MITH',TO_DATE('17-DEC-1980', 'DD-MON-YYYY'));
INSERT INTO EMP VALUES (2, 'ALLEN', TO_DATE('20-FEB-1981', 'DD-MON-YYYY'));
INSERT INTO EMP VALUES (3, 'WARD',  TO_DATE('22-FEB-1981', 'DD-MON-YYYY'));
INSERT INTO EMP VALUES (4, 'JONES', TO_DATE('2-APR-1981',  'DD-MON-YYYY'));
INSERT INTO EMP VALUES (5, 'MARTIN',TO_DATE('28-SEP-1981', 'DD-MON-YYYY'));

SQL> SELECT ename
  2  FROM emp WHERE ename LIKE '%\%%' ESCAPE '\';

ENAME
----------
S%MITH

SQL>
Home »
Oracle »
Select » 

Where:
  1. Where clause
  2. dual table
  3. Comparison Operators
  4. ANY
  5. ALL
  6. LIKE, NOT LIKE
  7. IN, NOT IN
  8. Between...AND, NOT Between...AND
  9. IS NULL, IS NOT NULL
  10. Logical operator AND, OR, NOT
  11. Operator Precedence for AND, OR, NOT
Related: