There are many ways to fetch the first 5 characters of the string -
Employee Table
| emp_id | emp_name | alary | dept_id | manager_id |
|---|---|---|---|---|
| E1 | Rahul | 15000 | D1 | M1 |
| E2 | Manoj | 15000 | D1 | M1 |
| E3 | James | 55000 | D2 | M2 |
| E4 | Michael | 25000 | D2 | M2 |
| E5 | Ali | 20000 | D10 | M3 |
| E6 | Robin | 35000 | D10 | M3 |
Using SUBSTRING Function
The SUBSTRING() function extracts some characters from a string.
Syntax
SUBSTRING(string , start , length )
SELECT SUBSTRING(emp_name ,1,5) as 'Employee Name' FROM Employee;
Output
| Employee Name |
|---|
| Rahul |
| Manoj |
| James |
| Micha |
| Ali |
| Robin |
Using LEFT Function
The LEFT() function is used to extract a specific number of characters from the beginning of a string. This function is supported by several databases, including MySQL, MS SQL Server, and Access, but not by Oracle.
Syntax
LEFT(string, number_of_chars)
SELECT LEFT(emp_name ,5) as 'Employee Name' FROM Employee;
Output
| Employee Name |
|---|
| Rahul |
| Manoj |
| James |
| Micha |
| Ali |
| Robin |
Code Runner
Copy the below queries in the code runner to see the result
SELECT SUBSTRING(emp_name ,1,5) as 'Employee Name' FROM Employee;