Often in PostgreSQL you may want to extract the last N characters in a string field.
You can use the following syntax to do so:
SELECT RIGHT(team, 3) AS last_three
FROM athletes;
This particular example will extract the last three characters from each string in the team column of the table named athletes.
The resulting substring will be saved to a new column named last_three.
To select a different number of characters from the end of a string, simply change the 3 in the RIGHT function to a different number.
The following example shows how to use this syntax in practice.
Example: How to Select Last N Characters in a String in PostgreSQL
Suppose that we create the following table named athletes that contains information about various basketball teams:
-- create table named 'athletes'
CREATE TABLE athletes (
athleteID INTEGER PRIMARY KEY,
team TEXT,
points INTEGER,
assists INTEGER
);
-- add rows to the table
INSERT INTO athletes VALUES (0001, 'Mavs', 22, 5);
INSERT INTO athletes VALUES (0002, 'Hawks', 30, 12);
INSERT INTO athletes VALUES (0003, 'Kings', 12, 3);
INSERT INTO athletes VALUES (0004, 'Kings', 25, 9);
INSERT INTO athletes VALUES (0005, 'Mavs', 31, 14);
INSERT INTO athletes VALUES (0006, 'Mavs', 16, 3);
INSERT INTO athletes VALUES (0007, 'Celtics', 10, 5);
INSERT INTO athletes VALUES (0008, 'Celtics', 14, 13);
INSERT INTO athletes VALUES (0009, 'Nuggets', 20, 8);
INSERT INTO athletes VALUES (0010, 'Hawks', 26, 3);
-- view all rows in table
SELECT * FROM athletes;
athleteid | team | points | assists
-----------+---------+--------+---------
1 | Mavs | 22 | 5
2 | Hawks | 30 | 12
3 | Kings | 12 | 3
4 | Kings | 25 | 9
5 | Mavs | 31 | 14
6 | Mavs | 16 | 3
7 | Celtics | 10 | 5
8 | Celtics | 14 | 13
9 | Nuggets | 20 | 8
10 | Hawks | 26 | 3
Suppose that we would like to extract the last three characters from each string in the team column.
We can use the following syntax to do so:
SELECT team,
RIGHT(team, 3) AS last_three
FROM athletes;
team | last_three
---------+------------
Mavs | avs
Hawks | wks
Kings | ngs
Kings | ngs
Mavs | avs
Mavs | avs
Celtics | ics
Celtics | ics
Nuggets | ets
Hawks | wks
Notice that the resulting table contains a new column named last_three that contains the last three characters from each string in the team column.
Feel free to use similar syntax to select the last N characters from a string field in your own table.
Additional Resources
The following tutorials explain how to perform other common tasks in PostgreSQL:
PostgreSQL: Extract Substring Before Specific Character
PostgreSQL: Extract Substring After Specific Character
PostgreSQL: How to Extract Substring Between Two Characters
