PostgreSQL String() Function: Extract the last four characters of phone numbers
9. Write a query to extract the last four characters of phone numbers.
Sample Solution:
Code:
-- This SQL query retrieves the last 4 digits of the phone numbers of employees and labels the column as "Ph.No.".
SELECT RIGHT(phone_number, 4) as "Ph.No." -- Retrieves the last 4 digits of the phone numbers and labels the column as "Ph.No."
FROM employees; -- Specifies the table from which to retrieve data, in this case, the employees table
Explanation:
- This SQL query extracts the last 4 digits of the phone numbers of employees.
- The SELECT statement selects the last 4 digits of the phone numbers and labels the column as "Ph.No.".
- The RIGHT() function is used to extract the rightmost 4 characters from the phone_number column.
- The phone_number column is assumed to store phone numbers.
- The result set will contain one column labeled as "Ph.No." with the last 4 digits of the phone numbers for each employee in the employees table.
Sample table: employees
Output:
pg_exercises=# SELECT RIGHT(phone_number, 4) as "Ph.No." pg_exercises-# FROM employees; Ph.No. -------- 4567 4568 4569 4560 5567 4561 4562 4563 4564 4567 4568 4565 4566 1934 1834 1734 1634 2034 2019 1834 8009 ... 7777 8888 8080 8181 (106 rows)
Practice Online
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a query to find all the employees which first name contains all the uppercase letter.
Next: Write a query to get the information about those locations which contain the characters in its street address is on and below the minimum character length of street_address.
What is the difficulty level of this exercise?
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/postgresql-exercises/string/postgresql-string-exercise-9.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics