Dollars and Quotes – PLpgSQL programming basics.

Start talking about dollars, and you will get all the attention in the world. Well, in this instance, it is not so much about dollars in the monetary sense, but more so in a programming one. You’re likely wondering just what on earth I am talking about. Read on and learn with me about a neat feature that PostgreSQL’s PLpgSQL procedural language provides when creating functions and stored procedures.

Photo by Olga DeLawrence on Unsplash

Note: All data, names or naming found within the database presented in this post, are strictly used for practice, learning, instruction, and testing purposes. It by no means depicts actual data belonging to or being used by any party or organization.

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!


I’ll use a couple of tables from the PostgreSQL practice DVD Rental database for the example queries below.

What is dollar quoting? To understand what dollar quoting is, we must first understand just what it offers in PLpgSQL programming terms.

Functions – and procedures – created in PLpgSQL are actually string literals. And, what’s the big deal about that?

In a nutshell, the function definition is essentially wrapped in single quotes (‘), meaning, any single quotes appearing in the function, must be escaped. And you guessed it, with another single quote.

I don’t have to tell you how cumbersome that can get. However, since I am a nice guy and all, I’ll provide a simple example of the madness this can pose and how to alleviate it with dollar quoting.

For the purpose of this post, we have this arbitrary query that returns the largest ‘country_id’ – via the MAX() aggregate function – for cities whose name begins with ‘Z’:

1
2
3
4
5
6
7
dvdrental=> SELECT MAX(country_id)
dvdrental-> FROM city
dvdrental-> WHERE city LIKE 'Z%';
 max
-----
  93
(1 row)

Perhaps we need to utilize that value on an on-going basis. Let’s write a PLpgSQL function both with and without dollar quoting to know the difference.

First, without dollar quoting, notice what happens if I try and execute the ‘get_country()’ function definition below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
CREATE OR REPLACE FUNCTION get_country()
RETURNS SMALLINT
AS
'
DECLARE c_id SMALLINT;
BEGIN
    SELECT MAX(country_id) INTO STRICT c_id FROM city
    WHERE city LIKE '
Z%';
    RETURN c_id;
END;
'
LANGUAGE PLpgSQL
dvdrental=> \i /path/to_sql_file/pg.sql
psql:/path/to_sql_file/pg.sql:41: ERROR:  syntax error at or near "Z"
LINE 8:  WHERE city LIKE 'Z%';

Since I did not escape both single quotes surrounding the Z letter in the LIKE predicate, the above error is returned. I’ll try again, however, this time, I will escape the single quotes with a single quote. (See how this can become messy.)

1
2
3
4
5
6
7
8
9
10
11
CREATE OR REPLACE FUNCTION get_country()
RETURNS SMALLINT
AS
'
DECLARE c_id SMALLINT;
BEGIN
    SELECT MAX(country_id) INTO STRICT c_id FROM city
    WHERE city LIKE '
'Z%'';
    RETURN c_id;
END;
'
LANGUAGE PLpgSQL

No errors during creation so let’s test out function ‘get_country()’:

1
2
3
4
5
dvdrental=> SELECT get_country();
 get_country
-------------
          93
(1 row)

All good there. Now to the crux of the post, dollar quoting. I’ll drop the function (not shown) then create this version:

1
2
3
4
5
6
7
8
9
10
11
CREATE OR REPLACE FUNCTION get_country()
RETURNS SMALLINT
AS
$$
DECLARE c_id SMALLINT;
BEGIN
    SELECT MAX(country_id) INTO STRICT c_id FROM city
    WHERE city LIKE 'Z%';
    RETURN c_id;
END;
$$ LANGUAGE PLpgSQL

Then call it:

1
2
3
4
5
dvdrental=> SELECT get_country();
 get_country
-------------
          93
(1 row)

This version works as intended like the previous one, but, the key difference here is notice where the $$ characters have replaced the single quotes (‘). By incorporating them, we no longer have to escape the single quotes surrounding ‘Z’ in the WHERE clause.

This version is easier to write, less prone to escaping issues, and more readable (in my opinion).

It goes without saying that your life will be much easier if you use dollar quoting when creating PLpgSQL functions and procedures. Be on the lookout for more blog posts about PLpgSQL programming.

Visit the excellent official documentation on dollar quoting for even more information and examples.

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

One thought on “Dollars and Quotes – PLpgSQL programming basics.

Hey thanks for commenting! Leave a Reply

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