Handy string functions: right() and left() with examples in PostgreSQL

In this blog post, I will visit a couple of handy string functions for extracting a specified number of characters from a string of text. Yet, with both functions, you can start from a certain position. Either left (beginning) or right (the end). Let’s see them in action with some examples…

Photo by Nick Fewings on Unsplash
OS and DB used:
  • Xubuntu Linux 18.04.2 LTS (Bionic Beaver)
  • PostgreSQL 11.2


Self-Promotion:

If you enjoy the content written here, by all means, share this blog and your favorite post(s) with others who may benefit from or like it as well. Since coffee is my favorite drink, you can even buy me one if you would like!


For these examples, I will use the ‘actor’ table from the mock DVD Rental practice database ported to Postgres, based on the open source SQL Sakila database.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
dvdrental=> \d actor;
                                            Table "public.actor"
   Column    |            Type             | Collation | Nullable |                 Default                
-------------+-----------------------------+-----------+----------+-----------------------------------------
 actor_id    | integer                     |           | not null | nextval('actor_actor_id_seq'::regclass)
 first_name  | character varying(45)       |           | not null |
 last_name   | character varying(45)       |           | not null |
 last_update | timestamp without time zone |           | not null | now()
Indexes:
    "actor_pkey" PRIMARY KEY, btree (actor_id)
    "idx_actor_last_name" btree (last_name)
Referenced by:
    TABLE "film_actor" CONSTRAINT "film_actor_actor_id_fkey" FOREIGN KEY (actor_id) REFERENCES actor(actor_id) ON UPDATE CASCADE ON DELETE RESTRICT
Triggers:
    last_updated BEFORE UPDATE ON actor FOR EACH ROW EXECUTE PROCEDURE last_updated()

Let’s dive right in with the left() function first:

1
2
3
4
5
6
7
8
9
dvdrental=> SELECT first_name, left(first_name, 2)
dvdrental-> FROM actor
dvdrental-> WHERE first_name LIKE 'V%';
 first_name | left
------------+------
 Vivien     | Vi
 Val        | Va
 Vivien     | Vi
(3 rows)

From the query results above, you can see that left() returned 2 characters from the left of the supplied string argument (or the first count of characters where count is the integer argument), in this case, the ‘first_name’ column. I only limited the returned number of rows via the WHERE clause with a predicate check for those names that start with ‘V’, for better on-screen visibility. The filter has nothing to do with the left() function.

The official documentation (see link below) defines the left() function as:

Return first n characters in the string. When n is negative, return all but last |n| characters.

As intelligent as you all are, I am sure you know what the right() function does then, right?

1
2
3
4
5
6
7
8
9
dvdrental=> SELECT first_name, right(first_name, 2)
dvdrental-> FROM actor
dvdrental-> WHERE first_name LIKE 'V%';
 first_name | right
------------+-------
 Vivien     | en
 Val        | al
 Vivien     | en
(3 rows)

You are correct!

The same is true for the right() function with the exception that right() extracts characters from the right, or end of the string.

From the docs, right() is defined as:

Return last n characters in the string. When n is negative, return all but first |n| characters.

Have a look at the left() and right() string functions next time you need to remove a certain number of characters from a string at either its beginning or end. Note there is different functionality when the n argument is negative, and that is perhaps another post for another day…

Like what you have read? See anything incorrect? Please comment below and thanks for reading!!!

Explore the official PostgreSQL 11 On-line Documentation for more information.

A Call To Action!

Thank you for taking the time to read this post. I truly hope you discovered something interesting and enlightening. Please share your findings here, with someone else you know who would get the same value out of it as well.

Visit the Portfolio-Projects page to see blog post/technical writing I have completed for clients.

Have I mentioned how much I love a cup of coffee?!?!

To receive email notifications (Never Spam) from this blog (“Digital Owl’s Prose”) for the latest blog posts as they are published, please subscribe (of your own volition) by clicking the ‘Click To Subscribe!’ button in the sidebar on the homepage! (Feel free at any time to review the Digital Owl’s Prose Privacy Policy Page for any questions you may have about: email updates, opt-in, opt-out, contact forms, etc…)

Be sure and visit the “Best Of” page for a collection of my best blog posts.


Josh Otwell has a passion to study and grow as a SQL Developer and blogger. Other favorite activities find him with his nose buried in a good book, article, or the Linux command line. Among those, he shares a love of tabletop RPG games, reading fantasy novels, and spending time with his wife and two daughters.

Disclaimer: The examples presented in this post are hypothetical ideas of how to achieve similar types of results. They are not the utmost best solution(s). The majority, if not all, of the examples provided, is performed on a personal development/learning workstation-environment and should not be considered production quality or ready. Your particular goals and needs may vary. Use those practices that best benefit your needs and goals. Opinions are my own.

Advertisements

2 thoughts on “Handy string functions: right() and left() with examples in PostgreSQL

Hey thanks for commenting! Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.