Thursday, May 11, 2017

SQL: substring of a string field - get the first number of characters of a string in Oracle

For example, you would like a list of employees whose first names start with "Chr", the SUBSTR function would help you to achieve it.

SUBSTR takes three arguments, the field name, the beginning position (starting from 1), and the length of the substring.

SQL> select firstName, middleName, lastName, title, department from employee
           where SUBSTR (firstName, 1, 3) = 'Chr';

The output will look something like:

firstName                middleName                   lastName            title                    department
----------------           ------------------                ---------------      ------------             --------------
Christine                  Anna                              Arendt                   librarian               Library
Christopher                                                     Jones                  security guard        Security


If you would like to display only the first four characters of the department:

SQL> select firstName, middleName, lastName, title, SUBSTR(department, 1,4) as department
           from employee
           where SUBSTR (firstName, 1, 3) = 'Chr';

The output would look something like:

firstName                middleName                   lastName            title                    department
----------------           ------------------                ---------------      ------------             --------------
Christine                  Anna                              Arendt                   librarian               Libr
Christopher                                                     Jones                  security guard        Secu


---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

No comments:

Post a Comment