Home > Blockchain >  Get all employee detail from employees table whose "First_name" start with any single char
Get all employee detail from employees table whose "First_name" start with any single char

Time:05-05

SELECT
    *
FROM
    employees
WHERE
    first_name LIKE 'A%'
    OR first_name LIKE 'B%'
    OR first_name LIKE 'C%'
    OR first_name LIKE 'D%'
ORDER BY
    first_name;

is there any new way to rewrite the SQL Query to find the first_name starting from A to P

CodePudding user response:

Isn't that just

SQL>   SELECT *
  2      FROM emp
  3     WHERE ename BETWEEN 'A' AND 'P'
  4  ORDER BY ename;

     EMPNO ENAME      JOB              MGR HIREDATE        SAL       COMM     DEPTNO
---------- ---------- --------- ---------- -------- ---------- ---------- ----------
      7876 ADAMS      CLERK           7788 12.01.83       1265                    20
      7499 ALLEN      SALESMAN        7698 20.02.81       1680        300         30
      7698 BLAKE      MANAGER         7839 01.05.81       2993                    30
      7782 CLARK      MANAGER         7839 09.06.81       2818                    10
      7902 FORD       ANALYST         7566 03.12.81       3450                    20
      7900 JAMES      CLERK           7698 03.12.81        998                    30
      7566 JONES      MANAGER         7839 02.04.81       3421                    20
      7839 KING       PRESIDENT            17.11.81       5750                    10
      7654 MARTIN     SALESMAN        7698 28.09.81       1313       1400         30
      7934 MILLER     CLERK           7782 23.01.82       1495                    10

10 rows selected.

SQL>

CodePudding user response:

Use SUBSTR to extract the first character and then compare that:

SELECT *
FROM   employees
WHERE  SUBSTR(first_name, 1, 1) BETWEEN 'a' AND 'p'
ORDER BY
       first_name;

or you could use:

SELECT *
FROM   employees
WHERE  (first_name BETWEEN 'a' AND 'p' OR first_name LIKE 'p%')
ORDER BY
       first_name;

(Which would use an index on first_name, whereas the first query would not use the index and, instead, would need a function-based index on SUBSTR(first_name, 1, 1).)

CodePudding user response:

Use regexp_like:

select *
from employees
where regexp_like(first_name, '^[a-p]', 'i')

The regex breakdown:

  • ^ means "start of text"
  • [a-p] means "any character in the range à to p inclusive"
  • The i flag means "ignore case"
  • Related