50% found this document useful (2 votes)
57 views

Procedural Programming with PostgreSQL PL/pgSQL: Design Complex Database-Centric Applications with PL/pgSQL 1 / converted Edition Baji Shaik instant download

The document promotes the book 'Procedural Programming with PostgreSQL PL/pgSQL' by Baji Shaik and Dinesh Kumar Chemuduru, which focuses on designing complex database-centric applications using PL/pgSQL. It provides a comprehensive guide on PL/pgSQL features, functionalities, and application scenarios, along with practical use cases and best practices. Additionally, it includes links to download the book and other related resources available on ebookmass.com.

Uploaded by

josolkolbet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
50% found this document useful (2 votes)
57 views

Procedural Programming with PostgreSQL PL/pgSQL: Design Complex Database-Centric Applications with PL/pgSQL 1 / converted Edition Baji Shaik instant download

The document promotes the book 'Procedural Programming with PostgreSQL PL/pgSQL' by Baji Shaik and Dinesh Kumar Chemuduru, which focuses on designing complex database-centric applications using PL/pgSQL. It provides a comprehensive guide on PL/pgSQL features, functionalities, and application scenarios, along with practical use cases and best practices. Additionally, it includes links to download the book and other related resources available on ebookmass.com.

Uploaded by

josolkolbet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

Download the full version and explore a variety of ebooks

or textbooks at https://ebookmass.com

Procedural Programming with PostgreSQL PL/pgSQL:


Design Complex Database-Centric Applications with
PL/pgSQL 1 / converted Edition Baji Shaik

_____ Tap the link below to start your download _____

https://ebookmass.com/product/procedural-programming-with-
postgresql-pl-pgsql-design-complex-database-centric-
applications-with-pl-pgsql-1-converted-edition-baji-shaik/

Find ebooks or textbooks at ebookmass.com today!


Here are some recommended products for you. Click the link to
download, or explore more at ebookmass.com

Procedural Programming with PostgreSQL PL/pgSQL: Design


Complex Database-Centric Applications with PL/pgSQL 1st
Edition Baji Shaik
https://ebookmass.com/product/procedural-programming-with-postgresql-
pl-pgsql-design-complex-database-centric-applications-with-pl-
pgsql-1st-edition-baji-shaik/

Oracle PL/SQL by Example, 6th Edition Benjamin Rosenzweig

https://ebookmass.com/product/oracle-pl-sql-by-example-6th-edition-
benjamin-rosenzweig/

Modern Oracle Database Programming: Level Up Your Skill


Set to Oracle’s Latest and Most Powerful Features in SQL,
PL/SQL, and JSON 1st Edition Alex Nuijten
https://ebookmass.com/product/modern-oracle-database-programming-
level-up-your-skill-set-to-oracles-latest-and-most-powerful-features-
in-sql-pl-sql-and-json-1st-edition-alex-nuijten-2/

Modern Oracle Database Programming: Level Up Your Skill


Set to Oracle’s Latest and Most Powerful Features in SQL,
PL/SQL, and JSON 1st Edition Alex Nuijten
https://ebookmass.com/product/modern-oracle-database-programming-
level-up-your-skill-set-to-oracles-latest-and-most-powerful-features-
in-sql-pl-sql-and-json-1st-edition-alex-nuijten/
Oracle Database Programming with Visual Basic.NET:
Concepts, Designs and Implementations Ying Bai

https://ebookmass.com/product/oracle-database-programming-with-visual-
basic-net-concepts-designs-and-implementations-ying-bai/

Starting Out With Programming Logic and Design, 6e 6th


Edition Tony Gaddis

https://ebookmass.com/product/starting-out-with-programming-logic-and-
design-6e-6th-edition-tony-gaddis/

Microsoft Power Platform Fundamentals. Exam Ref PL-900,


Second Edition Craig Zacker

https://ebookmass.com/product/microsoft-power-platform-fundamentals-
exam-ref-pl-900-second-edition-craig-zacker/

Programming Kotlin Applications: Building Mobile and


Server-Side Applications With Kotlin Brett Mclaughlin

https://ebookmass.com/product/programming-kotlin-applications-
building-mobile-and-server-side-applications-with-kotlin-brett-
mclaughlin/

Programming for Game Design: A Hands-On Guide with Godot


1st Edition Wang

https://ebookmass.com/product/programming-for-game-design-a-hands-on-
guide-with-godot-1st-edition-wang/
Baji Shaik and Dinesh Kumar Chemuduru

Procedural Programming with


PostgreSQL PL/pgSQL
Design Complex Database-Centric Applications
with PL/pgSQL
Baji Shaik
Texas, TX, USA

Dinesh Kumar Chemuduru


Andhra Pradesh, India

ISBN 978-1-4842-9839-8 e-ISBN 978-1-4842-9840-4


https://doi.org/10.1007/978-1-4842-9840-4

© Baji Shaik and Dinesh Kumar Chemuduru 2023

This work is subject to copyright. All rights are solely and exclusively
licensed by the Publisher, whether the whole or part of the material is
concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in
any other physical way, and transmission or information storage and
retrieval, electronic adaptation, computer software, or by similar or
dissimilar methodology now known or hereafter developed.

The use of general descriptive names, registered names, trademarks,


service marks, etc. in this publication does not imply, even in the
absence of a specific statement, that such names are exempt from the
relevant protective laws and regulations and therefore free for general
use.

The publisher, the authors, and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, expressed or implied, with respect to the
material contained herein or for any errors or omissions that may have
been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.
This Apress imprint is published by the registered company APress
Media, LLC, part of Springer Nature.
The registered company address is: 1 New York Plaza, New York, NY
10004, U.S.A.
I extend this dedication to Afrah Razzak, my exceptional wife. Her
enduring support and remarkable patience during the extended writing
sessions have been invaluable to me.
—Baji Shaik
I lovingly extend this dedication to my dear friend, Baji Shaik. Your
unwavering support and encouragement have been my guiding light,
especially in the most challenging moments. Your belief in me has been a
constant source of inspiration, and I am grateful for your presence in my
journey. This book is as much a tribute to our friendship as it is a
testament to the power of steadfast camaraderie. Thank you for always
being there.
—Dinesh Kumar Chemuduru
Introduction
The PostgreSQL engine comes with its own dedicated procedural
language, similar to procedural languages found in other commercial
database engines. This language, known as PL/pgSQL, offers a range of
powerful features that developers have long desired. For instance,
PL/pgSQL includes certain object-oriented programming capabilities
like the ability to define custom operators and types, as well as custom
aggregates.
In contrast to other programming languages supported by
PostgreSQL, PL/pgSQL is intricately linked with the PostgreSQL
database engine interface. This tight integration ensures optimal
performance and a seamless fit for constructing business logic on the
database side. In this book, we not only introduce the fundamentals of
PL/pgSQL, but we also dive deep into specific use cases that we’ve
implemented for particular scenarios. Our aim is to comprehensively
cover the various features, functionalities, and application scenarios of
PL/pgSQL, offering assistance in crafting effective server-side objects
with ease.
Through the content of this book, you will gain an understanding of
PL/pgSQL’s design and dive deep into its transaction model, including
how commit and rollback operations function. You’ll discover strategies
for optimizing PL/pgSQL functions and procedures and explore the
mechanics of inline or anonymous server-side code, along with its
limitations. Furthermore, you’ll acquire insights into debugging and
profiling PL/pgSQL code and learn techniques for conducting statistical
analyses on the PL/pgSQL code you create.
Any source code or other supplementary material referenced by the
author in this book is available to readers on GitHub
(https://github.com/Apress). For more detailed information, please
visit https://www.apress.com/gp/services/source-code.
Acknowledgments
I would like to express my gratitude to several individuals who have
played a crucial role in making this book a reality. A heartfelt thank-you
to Apress Media for providing me with this valuable opportunity. I am
especially grateful to my coauthor and mentor, Dinesh Kumar
Chemuduru, for his exceptional collaboration. I want to express my
gratitude to Divya Modi and Nirmal Selvaraj for being understanding of
our hectic schedules and providing us with continuous support
throughout the entire process. Special thanks to Deepak Mahto for his
thorough review of the book. Lastly, I am profoundly thankful to my
parents, Lalu Saheb Shaik and Nasar Bee, whose unwavering support
has shaped me into the person I am today.

—Baji Shaik

I would like to extend my heartfelt gratitude to a remarkable group


of individuals who have been instrumental in making this endeavor a
reality. My heartfelt thank-you to Apress Media for providing me with
this valuable opportunity. A special note of appreciation to my
esteemed coauthor, Baji Shaik. Sincere thanks to Deepak Mahto, whose
meticulous review and insightful feedback significantly enhanced the
quality and depth of this manuscript. To Divya Modi and Nirmal
Selvaraj, our project coordinators, your organizational skills and
dedication ensured that every aspect of this project fell seamlessly into
place. To my parents Vanamma, Sreenivasulu and my dearest children,
Yashvi and Isha, and to the future luminaries, Hema Siri K and Rahul
Sonu K – your unwavering love and understanding throughout the
demanding phases of this project have served as my steadfast anchor.
Your continuous support is my driving force.
Finally, a heartfelt thank-you to my exceptional team at Tessell. Your
commitment to excellence and innovation is awe-inspiring. Together,
we are shaping the future of DBaaS, and I am privileged to work
alongside such talented individuals.

—Dinesh Kumar Chemuduru


Table of Contents
Chapter 1:​Introduction to PL/​pgSQL
A Closer Look at PL/​pgSQL
PL/​pgSQL Installation
PL/​pgSQL Execution Flow
PL/​pgSQL Blocks
Anonymous or Unnamed Blocks
Named Blocks
Summary
What’s Next
Chapter 2:​PL/​pgSQL Variables
What Are Variables in PL/​pgSQL?​
Declaring Variables
Variable Scope
Constant Variables
Variable Alias
Scalar Variables
Array Variables
Record Variables
Cursor Variables
Summary
What’s Next
Chapter 3:​PL/​pgSQL Data Types
Data Types
Declaring Variables with Data Types
Supported Types
Base Type
Composite Type
Domain Type
Pseudo-Type
Range Type
Multirange Types
Summary
What’s Next
Chapter 4:​Dealing with Strings, Numbers, and Arrays
Strings
Function Format
Dealing with Null String
Numbers
Arrays
Example Use Cases
Strings
Numbers
Arrays
Summary
What’s Next
Chapter 5:​Control Statements
IF/​ELSE Statement
Cascading IF Statements
CASE Statement
Iterative Statement
LOOP Statement
WHILE Statement
FOR Statement
Example Use Cases
Example 1
Example 2
Best Practices of Using Control Statements in PL/​pgSQL
Summary
What’s Next
Chapter 6:​Handling Arrays
Array Index
Array Length
Iterate Array
Find Duplicate Elements in Array
Append Elements to Array
Array Merge
Multidimensional​Arrays
Summary
What’s Next
Chapter 7:​Handling JSON
What Is JSON?​
Use Cases
Advantages and Disadvantages
Build PL/​pgSQL Functions for JSON
Indexing JSON Data
Other Useful JSON Functions
Summary
What’s Next
Chapter 8:​Cursors
What Are Cursors?​
CURSOR Attributes
ISOPEN Attribute
FOUND Attribute
NOTFOUND Attribute
ROWCOUNT Attribute
Monitor Cursors
SCROLL Cursor
NO SCROLL Cursor
WITH HOLD Cursors
Refcursors
Summary
What’s Next
Chapter 9:​Custom Operators
Built-In Operators
Creating a Custom Operator
Simple Example
SCENARIO 1:​Case-Insensitive Comparison
SCENARIO 2:​Custom Data Type Math
SCENARIO 3:​Date Differentiate Operator
SCENARIO 4:​Custom Operator for Data Classification
Advantages
Disadvantages
Summary
What’s Next
Chapter 10:​Custom Casting
Built-In Casts
Custom Casts
Creating a Custom Cast
Simple Example
SCENARIO 1:​Converting Custom Data Types
SCENARIO 2:​Custom Data Type to JSONB
Summary
What’s Next
Chapter 11:​Dynamic SQL
What Is Dynamic SQL?​
Syntax of Dynamic SQL in PL/​pgSQL
Simple Example
Use Cases of Dynamic SQL
Best Practices and Considerations for Dynamic SQL
1.​Preventing SQL Injection
2.​Sanitizing and Validating Inputs
3.​Security Concerns
4.​Performance Optimization
Summary
What’s Next
Chapter 12:​Building Functions and Procedures
Functions
Defining Functions
Calling Functions
Categories
Immutable Functions
STABLE Functions
VOLATILE Functions
Procedures
Temporary Functions/​Procedures
VARIADIC Functions/​Procedures
Best Practices
Summary
What’s Next
Chapter 13:​Return Values and Parameters
Return Values
Simple Example
Different Ways to Return Values
RETURNS
RETURNS SETOF
RETURNS TABLE
OUT
Simple Difference Matrix
Different Examples for Each RETURN Type
Using SELECT Statements
Using RETURNS TABLE
Using RETURN NEXT
Using RETURNS SETOF TABLE
Using RETURNS SETOF Data Type
Using RETURNS RECORD
Using RETURNS SETOF RECORD
Using OUT Parameters
Using INOUT Parameter
Summary
What’s Next
Chapter 14:​Handling Exceptions
Exceptions
GET DIAGNOSTICS
FOUND
Exceptions in PL/​pgSQL
Different Ways to Handle Exceptions in PL/​pgSQL
Using the BEGIN and END Statements
Using the RAISE Statement
Custom Exceptions
Rethrow Exceptions
ASSERT
Get Call Stack
Using the GET STACKED DIAGNOSTICS Statement
Advantages of Using Exceptions
Disadvantages of Using Exceptions
Summary
What’s Next
Chapter 15:​Triggers
What Are Triggers?​
Syntax
Simple Example
Types of Triggers in PostgreSQL
Row-Level Triggers
INSTEAD OF Triggers
Statement-Level Triggers
Event Triggers
Advantages of Triggers
Disadvantages of Triggers
DROP Triggers
Summary
What’s Next
Chapter 16:​Transaction Management
Nested Transactions
Exception Handling
Summary
What’s Next
Chapter 17:​Aggregates
Custom Aggregate
Simple Example
State Transition Function
Final Function
Creating Custom Aggregate
Create Type
Create State Transition Function
Create Aggregate
Final Function
Summary
What’s Next
Chapter 18:​Listen and Notify
Simple Example
Build Polling in psql
TCN Extension
Summary
What’s Next
Chapter 19:​PL/​pgSQL Essential Extensions
plprofiler Extension
Installation
Usage
plpgsql_​check Extension
Installation
Usage
Summary
Index
About the Authors
Baji Shaik
, currently serving as a Senior Database
Consultant at AWS Professional Services,
embarked on his journey into the world
of databases in 2011. Since then, his
expertise has encompassed an array of
database technologies, including Oracle,
PostgreSQL, EDB Postgres, Amazon RDS,
Amazon Aurora, Amazon Redshift, and
Greenplum. Baji’s extensive background
spans both depth and breadth,
showcasing his mastery in SQL/NoSQL
database technologies.
Baji stands out as a Database
Migration Expert, having successfully
developed numerous database solutions
that tackle complex business challenges,
particularly in migrating databases from on-premises environments to
Amazon RDS and Aurora PostgreSQL/MySQL. His prowess also extends
to performance optimization, having fine-tuned RDS/Aurora
PostgreSQL/MySQL databases to achieve remarkable performance
benchmarks.
With a passion for knowledge sharing, Baji has authored several
notable books on PostgreSQL, such as PostgreSQL Configuration,
Beginning PostgreSQL on the Cloud, and PostgreSQL Development
Essentials. His commitment to education and information
dissemination is further evident through his contributions to
conferences, workshops, and a multitude of insightful blogs within the
AWS blog community.

Dinesh Kumar Chemuduru


, an accomplished Principal Architect (OSS), brings a wealth of
experience to the realm of technology and open source solutions. With
a notable background at AWS as a
proficient database consultant, Dinesh
excelled in orchestrating numerous
successful database migrations. His
expertise extends to the open source
arena, where he has both crafted and
augmented solutions around
PostgreSQL, showcasing his commitment
to collaborative innovation.
A coding enthusiast at heart, Dinesh
finds joy in crafting applications using
Flutter, Golang, and C++, platforms
where his creativity knows no bounds. His proficiency extends to the
deployment phase, as he deftly navigates Kubernetes to bring his
coding creations to life. In the literary domain, Dinesh stands as a
coauthor of the esteemed PostgreSQL High Performance Cookbook, a
testament to his mastery of the subject matter. Beyond his own works,
he actively engages in the appraisal of fellow authors’ PostgreSQL
books, cementing his status as a valued participant in the exchange of
knowledge.
Dinesh’s impact reverberates through his open source
contributions, which include the inception and enrichment of projects
such as PTOR – an ingenious RPO/RTO/SLA calculator tailored for
PostgreSQL. Another tool, “hammerpost,” sets a benchmark for
synthetic parameter evaluation in PostgreSQL, seamlessly integrated
with HammerDB.
About the Technical Reviewer
Deepak Ramnandan Mahto
works as a PostgreSQL Database
Engineer at Google Cloud. He has been
working with PostgreSQL since 2018,
and he also worked as a database
migration consultant at AWS. He is also a
keen blogger and loves to publish
articles on migration, best practices, and
on cloud with PostgreSQL. He loves to
code and build database-related utilities
using PL/pgSQL and SQL.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2023
B. Shaik, D. K. Chemuduru, Procedural Programming with PostgreSQL PL/pgSQL
https://doi.org/10.1007/978-1-4842-9840-4_1

1. Introduction to PL/pgSQL
Baji Shaik1 and Dinesh Kumar Chemuduru2
(1) Texas, TX, USA
(2) Andhra Pradesh, India

In this chapter, we will start with an introduction of PL/pgSQL, on what is


PL/pgSQL and what are the key features of it. We will talk about some
common use cases where PL/pgSQL is used. PL/pgSQL comes by default
when you install the PostgreSQL server. However, we will provide the
steps to install PL/pgSQL. We will explain how PL/pgSQL works with a
simple flow diagram. We will show some basic examples of PL/pgSQL
code blocks which are called anonymous and named code blocks.

A Closer Look at PL/pgSQL


PostgreSQL uses SQL (Structured Query Language) as a default query
language. SQL is a common domain-specific language for relational
databases. PostgreSQL uses some extensions and features to implement
the standards of SQL. In addition to SQL, PostgreSQL supports many
procedural languages like PL/pgSQL, PL/Java, PLV8, PL/Python, PL/Perl,
etc. Using these languages, you can create functions, stored procedures,
and triggers which will improve the performance by reducing the
multiple iterations to the databases.
PL/pgSQL is the most commonly used procedural language in
PostgreSQL. It is an extension of SQL. It is similar to Oracle's PL/SQL and
supports features like control structures, exception handling, variables,
loops, and conditional statements. These features help us to develop
complex database applications in an efficient way.
When working on designing a complex business logic inside the
database, you would need to develop multiple SQLs which are sometimes
interdependent. Results of one SQL will be used by other SQLs. In this
case, running multiple SQLs increases the data flow between the database
and the client application and will cause performance bottlenecks due to
high data transfer through the network. To overcome this, you can use
stored procedures or functions.
PL/pgSQL supports stored procedures, functions, and triggers. A
stored procedure is a set of precompiled SQL statements which can be
executed repeatedly. Stored procedures can help to reduce network traffic
and improve performance by reducing the amount of data that needs to
be sent between the database and the client application.
The common use cases to use stored procedures or functions using
PL/pgSQL are
1.
Improve data processing speed by using precompiled code through
stored procedures which will be faster than raw SQL queries.
2.
Write more complex code using features like control structures,
exception handling, variables, loops, conditional statements, etc.
3.
Using stored procedures or functions, you can create a reusable code
to call from the applications to save time and effort.
4.
PL/pgSQL is portable across different operating systems and
platforms. This makes it easier to migrate code between different
environments.
5.
Prevent unauthorized access and data breaches by controlling the
user authentication on stored procedures or functions.
6.
Use triggers to implement constraints of business processes that
cannot be expressed as foreign keys or check constraints.

PL/pgSQL Installation
PL/pgSQL is already included in PostgreSQL, so if you have PostgreSQL
installed, you should have PL/pgSQL as well. However, you may need to
enable it if it is not already enabled. Here are the steps to enable
PL/pgSQL in PostgreSQL:
1. Install PostgreSQL psql client to connect to the database, or you can
use the pgAdmin client tool.
For Ubuntu, the following are the simple steps to install the client:
# Create the file repository configuration:

sudo sh -c 'echo "deb


http://apt.postgresql.org/pub/repos/apt
$(lsb_release -cs)-pgdg main" >
/etc/apt/sources.list.d/pgdg.list'

# Import the repository signing key:

wget --quiet -O -
https://www.postgresql.org/media/keys/ACCC4CF8.asc
| sudo apt-key add -

# Update the package lists:

sudo apt-get update

# Install the latest version of PostgreSQL. If you want a specific


version, use 'postgresql-12' or similar instead of 'postgresql':

sudo apt-get -y install postgresql-client-15

For Linux (RHEL), you can follow the steps here:


2. www.postgresql.org/download/linux/redhat/
Connect to the database and check if PL/pgSQL is already installed:

postgres=# \dx
List of installed extensions
Name | Version | Schema | Description
-----+---------+--------+-------------
(0 rows)
postgres=# select * from pg_extension where
extname='plpgsql';
oid | extname | extowner | extnamespace |
extrelocatable | extversion | extconfig |
extcondition
----+---------+----------+--------------+---------
-------+------------+-----------+--------------
(0 rows)

3.
Execute the following command to enable PL/pgSQL:

postgres=# CREATE EXTENSION plpgsql;


CREATE EXTENSION

4.
Verify that PL/pgSQL is enabled by executing the following command:

postgres=# \dx
List of installed extensions
Name | Version
| Schema | Description
------ -+---------+------------+------------------
------------
plpgsql | 1.0 | pg_catalog | PL/pgSQL
procedural language
(1 row)
JavaScript
postgres=# select * from pg_extension where
extname='plpgsql';
oid | extname | extowner | extnamespace |
extrelocatable | extversion | extconfig |
extcondition
------+---------+----------+--------------+-------
---------+------------+-----------+-------------
16388 | plpgsql | 10 | 11 |
f | 1.0 | |
(1 row)

PL/pgSQL Execution Flow


PL/pgSQL is like every other “loadable, procedural language.” PL/pgSQL
gets loaded through a function manager called fmgr. The fmgr loads the
language handler when a procedural language function or procedure is
executed and calls it. The execution flow of PL/pgSQL code is similar to
that of other procedural programming languages, with parsing,
compilation, execution, and cleanup stages. However, PL/pgSQL code is
executed on the server side, which means that it has direct access to the
database and can perform database operations more efficiently than
client-side code.
On the first call of a PL/pgSQL function or procedure in a session, the
server first parses the code to check for syntax errors. The call handler
will “compile” a function statement tree once the code is parsed. When
the code is compiled, it turns into an internal form that the server can
execute more efficiently. SQL queries in the function are just kept as a
string at this point, and the expressions like the following are actually SQL
queries:

my_var := some_param * 10

The SQL queries are actually parsed at this point, and parser hooks
are used to replace variables/parameters with PARAM nodes in the parse
tree. The PL/pgSQL statement tree is very similar to a PostgreSQL
execution tree. After the parse and compile, the call handler then executes
that statement tree. On the first execution of a statement node that has an
SQL query in it, that query is prepared via the Server Programming
Interface (SPI). The SPI provides a simple and efficient way to execute
SQL commands, retrieve query results, and manipulate the database. The
compiled code is then executed by the server. Based on any variable and
control structure declaration, the server creates a new execution
environment for the PL/pgSQL code. If the PL/pgSQL code is a function or
stored procedure that returns a result set, the server will send the result
set back to the client. Once the execution of the code is complete, the
server will clean up any resources that were used by the PL/pgSQL code,
including variables and any temporary tables that were created.
Figure 1-1 represents the flow of execution.
Figure 1-1 PL/pgSQL execution flow

This diagram illustrates the high-level steps of the PL/pgSQL


execution flow. However, it's important to note that PL/pgSQL code can be
quite complex and may include multiple control structures, error
handling blocks, and nested and even recursive PL/pgSQL function calls
and trigger invocations and database operations. The actual execution
flow of a specific PL/pgSQL function or stored procedure will depend on
the specific code and logic used. This call hierarchy is not limited to
PL/pgSQL. All procedural languages share the common entry point of the
fmgr, so they can be mixed and matched in trigger and function call
stacks.

PL/pgSQL Blocks
PL/pgSQL is a block-structured language. The basic unit in any PL/pgSQL
code is a block. All PL/pgSQL code is composed of a single block or blocks
that occur either sequentially or nested within another block. There are
two kinds of blocks:
Anonymous or unnamed blocks (DO)
Named blocks (functions)

Anonymous or Unnamed Blocks


Anonymous or unnamed blocks are generally constructed dynamically
and executed only once by the user. It is sort of a complex SQL statement.
The following is the structure of an anonymous block, for example:

DO $$
[ <<label>> ]
[ DECLARE
-- Variable declaration here
]
BEGIN
-- Execute statements here
END [ label ];
$$;

Now, let us start with a simple hello world code block, which does not
have any name associated with it:

postgres=# DO
$$
BEGIN
RAISE NOTICE 'Hello World';
END;
$$;
NOTICE: Hello World
DO

In the preceding example, the RAISE NOTICE command will help


us to print the given message on the client console. As you can see here,
the block is declared without a name, and if you want to print Hello
World, then you have to repeat the same set of instructions again.
Now, let us print the Hello World line by line rather than in a single
line:

postgres=# DO
$o$
BEGIN
RAISE NOTICE $i$
Hello
World
$i$;
END;
$o$;

NOTICE:
Hello
World
DO

In the preceding example, we used different multiline specifiers. The


whole block got enclosed by $o$, and the inner Hello World got
enclosed by $i$. From this example, we can learn that in PL/pgSQL, we
can have the nested multiliners, where each multiline should follow its
own enclosure.
Now, let us write a nested BEGIN ... END inside a main BEGIN
... END block. Here is an example:

postgres=# DO
$$
BEGIN

BEGIN
RAISE NOTICE 'Hello World';
END;
END;
$$;
NOTICE: Hello World
DO

In the preceding example, we print the Hello World message from


the nested BEGIN ... END block. It is possible to have multiple nested
statements inside a single BEGIN...END block. We will see more of
these in the coming chapters, where we discuss exception handling.
Now, let us go a little deeper and print the Hello World message
from the nested unnamed code block:

postgres=# DO
$o$
BEGIN
DO
$i$
BEGIN
RAISE NOTICE 'Hello World';
END;
$i$;
END;
$o$;
NOTICE: Hello World
DO

As you can see in the preceding example, we are able to define an


unnamed block inside an unnamed block. By defining the nested code
blocks, we can segregate a large unnamed block into multiple stand-alone
work units. We don’t need to write a nested unnamed block; in most of
the cases, the nested BEGIN...END block would be sufficient. But in
general, we don’t keep large unnamed blocks in the database; rather, we
store them inside with a name (function/procedure), and we call that
object name, whenever it is required.
Here is another example where we can have a nested block inside an
exception:
postgres=# DO $inline$
BEGIN
PERFORM 1/0;
RAISE NOTICE 'Hello World!';

EXCEPTION
WHEN OTHERS THEN
DO $$
BEGIN
RAISE NOTICE 'Got error';
END;
$$;
END;
$inline$;
NOTICE: Got error
DO

PL/pgSQL does not restrict the anonymous blocks as stand-alone


objects; we can also embed these inline definitions inside the function or
procedure object. We haven’t discussed about procedures and
functions yet, but showing you an example where you can declare the
inline anonymous block inside a function:

postgres=# CREATE OR REPLACE FUNCTION test_func()


RETURNS void
LANGUAGE plpgsql
AS $function$
BEGIN
DO $$ BEGIN RAISE NOTICE 'Hello World!';
END;$$;
END;
$function$;
CREATE FUNCTION

postgres=# SELECT test_func();


NOTICE: Hello World!
test_func
-----------
(1 row)

How it works is, unlike other procedural languages, PL/pgSQL gives


an inline statement handler plpgsql_inline_handler. By using this
handler, PL/pgSQL executes the unnamed or inline PL/pgSQL blocks. If
there are any nested code blocks, then those will be evaluated recursively
by the plpgsql_inline_handler.

Note that it is not possible to return any value from the unnamed

code blocks. Always use anonymous code blocks to define the business
logic, which involves making a set of function or procedure calls. If you
want to return any value from anonymous blocks, then we might need
to use any session-level variables, which need to be set inside the
anonymous block, and access them from the outside of the blocks.

Named Blocks
Named blocks have a name associated with them, are stored in the
database, can be executed repeatedly, and can take in parameters.
A named block in PL/pgSQL is defined using the following syntax:

<<label>>
DECLARE
-- declare variables here
BEGIN
-- Named block's code here
END;

Here, label is the name of the block and is enclosed within << >>
brackets.It is not just cosmetic, but that nested code blocks can refer to
outer variables by using that label instead of finding the innermost match
for the variable name.
The DECLARE section is used to declare variables that are used within
the block, while the BEGIN and END sections contain the actual code for
the block.
Once a named block has been defined, it can be called from within the
same function or procedure using the PERFORM statement:

PERFORM block_name;

This will execute the code within the named block. Named blocks can
be called multiple times within the same function or procedure, allowing
for reusable and modular code.
Here's an example of a PL/pgSQL function that uses named blocks to
calculate the factorial of a number:

CREATE OR REPLACE FUNCTION factorial(num INTEGER)


RETURNS INTEGER AS $$
DECLARE
result INTEGER := 1;
BEGIN
<<factorial_loop>>
FOR i IN 1..num LOOP
result := result * i;
END LOOP factorial_loop;

RETURN result;
END;
$$ LANGUAGE plpgsql;

In this example, the named block factorial_loop is used within a FOR


loop to calculate the factorial of the input number. The DECLARE section
declares a variable result to store the final result, while the BEGIN and
END sections contain the code for the named block.
The named block is called within the FOR loop using the LOOP
statement. This allows the loop to continue until it reaches the specified
number of iterations.
Once the FOR loop is complete, the final result is returned by the
function.
To call the function and calculate the factorial of a number, you would
execute the following SQL statement:

SELECT factorial(5);
This would return the value 120, which is the factorial of 5.

Summary
In this chapter, we talked about PL/pgSQL use cases, installation, and how
it works with a flow diagram. We have also shown how simple PL/pgSQL
code blocks look like and how to execute them. These examples will help
you to understand and start with PL/pgSQL code. In the next chapter, we
will talk about the variables that are used inside PL/pgSQL code blocks.
We will start with how to declare those variables and dive deep into
different types of methods to use based on the use cases. These will help
you to decide which type of variables you should use when building the
PL/pgSQL code for the functions or procedures.

What’s Next
In the next chapter, we will be covering some key features of PL/pgSQL
variables like the following:
Variable Types: Explore the different types of variables and learn how
to choose the appropriate variable type for your needs.
Variable Scoping Mastery: Gain a better grasp of variable scoping
rules and how to manage variables effectively within different blocks.
Variable Naming Conventions: Learn about naming conventions that
can help you write more maintainable and readable code.
Advanced Variable Usage: Extend your knowledge by using variables
in more complex scenarios.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2023
B. Shaik, D. K. Chemuduru, Procedural Programming with PostgreSQL PL/pgSQL
https://doi.org/10.1007/978-1-4842-9840-4_2

2. PL/pgSQL Variables
Baji Shaik1 and Dinesh Kumar Chemuduru2
(1) Texas, TX, USA
(2) Andhra Pradesh, India

In the previous chapter, we talked about what PL/pgSQL is and some


use cases where you need it. We also explained the steps to install and
the execution flow of PL/pgSQL with a simple diagram. We have
discussed some PL/pgSQL anonymous and named code block examples
which will help in understanding the basics. In this chapter, we will
introduce variables that are used in the PL/pgSQL code. We will
provide different types of variables and use cases on when to use them.
We will show the declaration and scope of variables and different types
of variables with some examples.

What Are Variables in PL/pgSQL?


Similar to other programming languages, PL/pgSQL has variables
which are used to store values for later use in the program. These
variables can hold different types of data such as integers, floating-
point numbers, strings, and boolean values.

Declaring Variables
PL/pgSQL offers to declare variables in its declaration section of the
block. Here is an example:

postgres=# DO
$$
DECLARE
v_var1 INT;
v_var2 INT:=10;
BEGIN
RAISE NOTICE 'v_var1 %', v_var1;
RAISE NOTICE 'v_var2 %', v_var2;
END;
$$;
NOTICE: v_var1 <NULL>
NOTICE: v_var2 10
DO

In the preceding example, we have declared two variables. The


v_var1 variable is declared but not defined with any value to it. The
second variable v_var2 is declared but has a value 10 to it. If we try to
access a variable which is declared and not defined, then expect that we
would get NULL from it. In the preceding output, we can also see that
the v_var1 is set to NULL.
From the previous chapter, we learned that we can have nested
blocks inside the main PL/pgSQL block. By using that nested block
feature, we have multiple declarations and multiple variables in the
single PL/pgSQL block. Here is an example:

postgres=# DO
$o$
DECLARE
v_var1 INT:=10;
BEGIN

RAISE NOTICE 'v_var1 %', v_var1;

DO
$i$
DECLARE
v_var1 INT:=100;
BEGIN
RAISE NOTICE 'v_var1 %', v_var1;
END;
$i$;

END;
$o$;
NOTICE: v_var1 10
NOTICE: v_var1 100
DO

In the preceding example, we have nested unnamed blocks, where


we have two variable declarations. The variable v_var1 in the main
block is declared with the value 10, and also v_var1 in the inside
block is declared with the value 100. Also, the scope of the variable is
always local.

Note In PL/pgSQL, we can’t declare variables on the fly. We should


always declare them in the DECLARE section, and we have to use
them in the block. But, while defining the FOR LOOP, we can have
the variables declared on the fly. We will discuss more about this in
the coming chapters.

Variable Scope
The scope of the declared variables in PL/pgSQL is always local to its
current block. That is, once we declare the variable in a block, we can’t
access them outside of that block. Here is an example:

postgres=# DO
$$
DECLARE
BEGIN
DECLARE
v_var1 INT:=10;
BEGIN
RAISE NOTICE 'v_var1 %', v_var1;
END;
RAISE NOTICE 'v_var1 %', v_var1;
END;
$$;
NOTICE: v_var1 10
ERROR: column "v_var1" does not exist
LINE 1: v_var1
^
QUERY: v_var1
CONTEXT: PL/pgSQL function inline_code_block line
10 at RAISE

From the preceding example, as you can see we got an error,


column "v_var1" does not exist, when we try to access the
variable v_var1 from the outer BEGIN...END block. That is, the
scope of variable v_var1 is local to that inner BEGIN...END block,
and we can’t access them from the outside. If we declare the variable
v_var1 in the parent BEGIN...END block, then we can access that
variable inside the nested BEGIN...END blocks too. Because the
v_var1 is declared at the parent block level, its scope is at the whole
block level. Now, you might have questions like what if we declare the
same variable v_var1 in parent and nested BEGIN...END blocks and
how to access the parent block’s v_var1 along with the local declared
variable. Here is an example for this use case:

postgres=# DO
$$
DECLARE
v_var1 INT:=1;
BEGIN
DECLARE
v_var1 INT:=10;
BEGIN
RAISE NOTICE 'v_var1 %', v_var1;
END;
END;
$$;
NOTICE: v_var1 10
DO

From the preceding example, we were only able to access the


variable v_var1, which was declared in the nested BEGIN...END
block. To access the parent v_var1 variable, then we should access
that variable with the block’s label. That is, we have to give a label name
to the parent block, and then we should access the v_var1 along with
its label name. Here is an example:

postgres=# DO
$$
<<parent>>
DECLARE
v_var1 INT := 1;
BEGIN
DECLARE
v_var1 INT := 10;
BEGIN
RAISE NOTICE 'Parent v_var1 %',
parent.v_var1;
RAISE NOTICE 'Local v_var1 %',
v_var1;
END;
END;
$$;
NOTICE: Parent v_var1 1
NOTICE: Local v_var1 10
DO

Constant Variables
We can declare constant variables inside PL/pgSQL, which shouldn’t get
updated by further instructions. Here is an example:

postgres=# DO
$$
DECLARE
v_c_pi CONSTANT REAL DEFAULT 3.14;
BEGIN
v_c_pi = 3.15;
END;
$$;
ERROR: variable "v_c_pi" is declared CONSTANT
LINE 6: v_c_pi = 3.15;

In the preceding example, we declared the variable v_c_pi as


CONSTANT and set its DEFAULT value as 3.14. But, in further
instructions, when we tried to update its value as 3.15, we got the
exception as the variable is declared as CONSTANT, which should not
get updated by any of the instructions.

Variable Alias
In PL/pgSQL, we can also create a reference variable which points to
another variable or system variables. For example, if we want to create
a reference variable or a short-length variable name to another
variable, then we can create those short-length variables using ALIAS.
Here is an example:

DO
$$
DECLARE
var_earth_sun_distance REAL DEFAULT 149.6;
v_e_s_d ALIAS FOR var_earth_sun_distance;
BEGIN
RAISE NOTICE 'Reference #1 %', v_e_s_d;
v_e_s_d = 149.5;
RAISE NOTICE 'Actual Variable %',
var_earth_sun_distance;
END;
$$;
NOTICE: Reference #1 149.6
NOTICE: Actual Variable 149.5
DO
In the preceding example, we created a reference variable v_e_s_d
to the actual variable var_earth_sun_distance. Also, if we
perform any update on the reference variable, then we can see those
changes from the actual variable. ALIAS is not limited to creating a
reference variable to the actual variable, it will allow creating a
reference to another reference. Here is an example:

DO
$$
DECLARE
var_earth_sun_distance REAL DEFAULT 149.6;
v_e_s_d ALIAS FOR var_earth_sun_distance;
vd ALIAS FOR v_e_s_d;
BEGIN
RAISE NOTICE 'Reference #1 %', v_e_s_d;
RAISE NOTICE 'Reference #2 %', vd;
RAISE NOTICE 'Update Ref #1';
v_e_s_d = 149.5;
RAISE NOTICE 'Actual Variable %',
var_earth_sun_distance;
RAISE NOTICE 'Update Ref #2';
vd = 149.4;
RAISE NOTICE 'Actual Variable %',
var_earth_sun_distance;
END;
$$;
NOTICE: Reference #1 149.6
NOTICE: Reference #2 149.6
NOTICE: Update Ref #1
NOTICE: Actual Variable 149.5
NOTICE: Update Ref #2
NOTICE: Actual Variable 149.4
DO

In the preceding example, we created an ALIAS variable from


another ALIAS variable. That is, we created a new reference variable,
which points to another reference variable. Also, if we update the
second reference variable, it will reflect those changes on the actual
variable via the first reference.
PL/pgSQL supports the following types of variables:
Scalar Variables
Array Variables
Record Variables
Cursor Variables

Scalar Variables
In all the previous examples, we demonstrated scalar variables. Scalar
variables hold a single value of a specific data type, such as an integer
or a string. They can be declared and initialized using the DECLARE
keyword and can be assigned values using the := assignment operator.
For example, the following code declares each type of scalar
variable:

postgres=# DO $$
DECLARE
my_int integer := 1;
my_text text := 'Hello, world!';
my_bool boolean := true;
BEGIN
-- perform operations on the scalar variables
my_int := my_int + 10;
my_text := my_text || ' How are you?';
my_bool := not my_bool;

-- print the scalar variables


RAISE NOTICE 'my_int = %', my_int;
RAISE NOTICE 'my_text = %', my_text;
RAISE NOTICE 'my_bool = %', my_bool;
END;
$$;
NOTICE: my_int = 11
NOTICE: my_text = Hello, world! How are you?
NOTICE: my_bool = f
DO
In the preceding example, we declare three scalar variables:
my_int with a value of 1 and a data type of integer, my_text with a
value of 'Hello, world!' and a data type of text, and my_bool
with a value of true and a data type of boolean. We then perform
some operations on these variables using arithmetic, concatenation,
and logical negation. Finally, we print the values of the variables using
the RAISE NOTICE statement.
Scalar variables are useful for storing temporary values or
performing calculations within a stored procedure or function. They
can be used in a variety of ways, such as tracking state, performing
conditional logic, or holding input or output parameters.

Array Variables
Array variables are variables that can hold multiple values of the same
data type. They are declared using a data type followed by the [] syntax,
such as integer[] or text[].
For example, the following code declares an array variable:

postgres=# DO $$
DECLARE
my_array integer[] := '{1, 2, 3, 4, 5}';
BEGIN
-- print the entire array
RAISE NOTICE 'my_array = %', my_array;

-- access individual elements of the array


RAISE NOTICE 'my_array[2] = %', my_array[2];

-- modify individual elements of the array


my_array[3] := 10;

-- print the modified array


RAISE NOTICE 'my_array = %', my_array;
END;
$$;
NOTICE: my_array = {1,2,3,4,5}
NOTICE: my_array[2] = 2
NOTICE: my_array = {1,2,10,4,5}
DO

In the preceding example, we declare an array variable my_array


with a data type of integer[] and initialize it with the values {1,
2, 3, 4, 5}. We then print the entire array using the RAISE
NOTICE statement, access and print the value of the second element of
the array, modify the value of the third element of the array, and print
the entire array again.
Array variables are useful for storing and manipulating sets of
related data, such as lists of numbers, strings, or boolean values. They
can be used in a variety of ways, such as for performing calculations on
multiple values at once, storing input or output parameters, or passing
data between functions or procedures.

Record Variables
Record variables are used to store a row of data from a table or a query
result. They are declared using the %ROWTYPE attribute and can be
assigned values using the SELECT INTO statement.
For example, the following code declares a record variable:

postgres=# CREATE TABLE emp (emp_id INT, emp_name


VARCHAR, emp_salary NUMERIC);
CREATE TABLE

postgres=# INSERT INTO emp VALUES (100, 'SCOTT',


'10000.00');
INSERT 0 1

postgres=# DO $$
DECLARE
my_record emp%ROWTYPE;
BEGIN
-- select a row of data into the record
variable
SELECT * INTO my_record FROM emp WHERE emp_id =
100;
-- print the values of the record variable
RAISE NOTICE 'emp_id = %', my_record.emp_id;
RAISE NOTICE 'emp_name = %',
my_record.emp_name;
RAISE NOTICE 'emp_salary = %',
my_record.emp_salary;

-- update the values of the record variable


my_record.emp_name := 'Smith';
my_record.emp_salary := 50000;

-- update the row of data in the table


UPDATE emp SET emp_name = my_record.emp_name,
emp_salary = my_record.emp_salary WHERE emp_id =
1001;
END;
$$;
NOTICE: emp_id = 100
NOTICE: emp_name = SCOTT
NOTICE: emp_salary = 10000.00
DO

In the preceding example, we declare a record variable my_record


that holds a row of data from the emp table. We then select a row of
data into the record variable using a SELECT statement, print the
values of the record variable using the RAISE NOTICE statement,
update the values of the record variable, and update the row of data in
the table using an UPDATE statement.
Record variables are useful for storing and manipulating rows of
data from tables or query results within a stored procedure or function.
They can be used in a variety of ways, such as for passing data between
functions or procedures, performing calculations on data, or storing
input or output parameters.

Cursor Variables
Cursor variables are variables that hold a reference to a cursor, which is
a named SQL statement that can be executed repeatedly. They are
Other documents randomly have
different content
The whole town here is ringing with a song, supposed to have a political
tendency against the French, and the journals are striving with all their
might to render it popular. In the present dearth of public topics, they
succeed in this without any difficulty, and every one is speaking of the
“Rheinlied” or the Colognaise, as they significantly call it. The thing is
characteristic, for the first line begins, “Sie sollen ihn nicht haben, den
freien Deutschen Rhein,” and at the commencement of each verse is
repeated “Never shall they have it,” as if there were the least sense in such
words! If they were at least changed into “We mean to keep it,”—but
“Never shall they have it” seems to me so sterile and futile. There is
certainly something very boyish in this idea; for when I actually possess an
object, and hold it sure and fast, it is quite superfluous to sing, or to say, that
it shall belong to no one else. This song is now sung at Court in Berlin, and
in the clubs and casinos here, and of course the musicians pounce upon it
like mad, and are immortalizing themselves by setting it. The Leipzig
composers have already brought out no less than three melodies for it, and
every day the papers make some allusion to it. Yesterday, amongst other
things, they said I had also set the song, whereas I never even dreamt of
meddling with such a merely defensive inspiration.
So the people here lie like print, just as they do with you, and
everywhere else.
To Paul Mendelssohn Bartholdy.
Leipzig, November 20th, 1840.
Dear Paul,
How much I wish that you would perform your promise, and come here
for the “Hymn of Praise;” I shall be glad to know what you think of it, and
to hear if it pleases you, for I own that it lies very near my heart. I think too
that it will be well executed by our orchestra; but in spite of this, if by
arriving in time for its performance, your proposed visit must be in any
degree shortened, then I would urge you to come on some other occasion,
for our happy quiet intercourse must always form the chief object in our
Leipzig life, and even one day more is pure gain. If indeed both could be
combined, a visit of the usual length and the concert, that would of course
be best of all. The “Hymn of Praise” is to form the second part; in the first,
probably Weber’s “Jubilee Overture” will be given, Kreuzer’s “Rheinlied”
and some other pieces. I could write you a long complaint about this said
“Rheinlied.” You can have no idea of the fuss they make about it here, and
how utterly repugnant to me this newspaper enthusiasm is; to make such a
piece of work about a song, the chief burden of which is, that others shall
not deprive us of what we have already got; truly this is worthy of such a
commotion and such music! I never wish to hear a single note of it sung,
when the refrain is always the resolve not to give up what you possess.
Young lads and timid men may make this outcry, but true men make no
such piece of work about what is their own; they have it, and that suffices. I
felt provoked to see recently in a newspaper, that in addition to four
compositions on these words, one by me had just appeared, and my name
was printed full length; yet I cannot give a direct contradiction to this, for as
regards the public I am dumb. At the same time Härtel sent me a message
that if I would compose for it, he would undertake to dispose of 6000 copies
in two months. No! Paul, I won’t do it. May we soon have a happy meeting!
—Your
Felix.
To Paul Mendelssohn Bartholdy.
Leipzig, December 7th, 1840.
Dear Brother,
Just as I was about to write to you yesterday, to thank you cordially
again and again for the fresh proof of your true brotherly love which you
have given me,[44] your letter arrived, and I can only repeat the same thing.
Even if the affair leads to nothing further than to show me (what is the fact)
that you participate in my wish once more to pass a portion of our lives
together, that you, too, feel there is something wanting when we are not all
united in one spot; this is to me invaluable, and more gratifying than I can
express. Whether it be attended with a happy result or not, I would not give
up such a conviction for anything in the world.
Your letter, indeed, demands mature deliberation, but I prefer replying to
it at once, for the coincidence of Herr Massow’s journey is most fortunate,
and you can thus hear my opinion before your interview with him.
I am prepared to acknowledge to the utmost extent the high honour
conferred on me, and the excellence of the position offered to me. On this
very account, however, I wish to obviate any difficulties, and to make the
matter as clear as possible. One thing occurs to me in the proposal, which
you can perhaps remedy in your conversation with Massow. It would not be
easy to explain it by letter, and at all events it would lose much time, and
not further the affair.
You may remember the general overtures as to the Academy and school
for music that you brought me, and you know that I named the concerts as a
positive stipulation; on the other hand, I said to you, that without a definite
sphere of work (as an appointed composer, like Grimms, you can say) I
should hesitate much to accept the proposal. Either of these situations
would suit me, but not the two combined. I would at once most decidedly
refuse this, much as I should regret being obliged to do so, and however
advantageous it might seem to me in other points. Your condition No. 2,
sets forth that I am to be director of the musical classes, without any
definite sphere of work, etc.; and then No. 4 declares that I am to give
sundry concerts every year,—but that is a combination to which I never can
consent. For instance, were I to undertake to give concerts in Berlin (and
the acceptance of these proposals would render it my duty so to do, even
towards you), then I must stand in a different relation to the orchestra from
what I could possibly do as the mere director of the music classes. I must be
quite as much their real chief there as I am here, and as every ordinary
director must be, which is only possible by the establishment of a Musical
Academy as a Royal Institution, and by its connection with the orchestra in
Berlin. The number, too, of such concerts should not be very limited, as you
say, otherwise they would not repay the trouble of such great preparations.
In a word, you may easily perceive that I can only accept proposals that
either define every point, or are confined to my personal, and not to my
official position; if the two are to be blended, I cannot consent to undertake
them.
Finding (after you left us) on more mature deliberation that a situation as
a composer is impossible, and, in fact, is nowhere to be met with, it
occurred to me that the offer might be renewed of a public sphere of
activity, and that I am quite prepared to accept; it must, however, be within
special limits, despotic as regards the musicians, and consequently
imposing even in outward position (not merely brilliant in a pecuniary point
of view), otherwise, according to my ideas, it would be fatal to my authority
after the very first rehearsal. I merely say all this, in order to indicate to you
the point of the compass for which you must steer your course, in your
conversation with Massow, and that the affair may pursue as clear a path as
possible.—Ever your
Felix.
To Paul Mendelssohn Bartholdy.
Leipzig, December 20th, 1840.
Dear Brother,
You wish to have some tidings from me as to our affair (for well may I
call it so). The letter from Massow came eight days since, and I answered it
on Wednesday, just as I would have written or spoken to yourself, without
reservation or disguise, but still without that eager acceptance which was
probably expected. I think you would have been satisfied with my letter,
and I hope and trust Massow may be so also. He wrote far less explicitly
about the details of the institution than you did in a former letter; he
mentions the salary, the direction of the classes, and the concerts to be given
by Royal command, but without entering into any further particulars. I
replied that I was so fully aware of the advantage and honour of his offer,
that I feared he would be surprised by my not instantly closing with it.
There was but one obstacle in the way, which was, that I did not precisely
know what was expected from me in return for such a proposal. I then
brought under his notice, the difficulties opposed to a bonâ fide direction of
the present classes; and as he had mentioned that these would not now
occupy much of my time, but that it was expected I should, under the new
system, undertake additional work, I begged, therefore, at least to be told
what were the limits of this system, and the duties I had to perform; that I
was indeed quite willing to work, but did not choose to pledge myself to the
performance of functions that were not precisely defined. With regard to the
concerts, I told him my opinion as to the only mode of arranging them now
in Berlin; that little good could accrue from merely occasional
performances, even by Royal command; for in that case all sorts of counter-
influences (and those I specified to him) would have full scope; that an
institute must be founded exclusively for similar concerts, and likewise
days fixed for the rehearsals and concerts, and the instruction of the
performers, etc.; that I would have nothing to do with the orchestra, except
on this condition, that I was to be absolute director-in-chief of these
concerts, etc.
In short, I showed that I was well disposed to accept the situation, but
should require the most unqualified support throughout, otherwise I could
not efficiently perform the duties of the office,—it being a public one. I
hope you agree with me on this point, for though money and ready
complaisance are indeed of no small value, still neither are sufficient,
without that entire tranquillity and security about the future, which can now
be given if they are in earnest in the matter. I can assure you that there was
no undue particularity in my words, but I am certain you will not blame me
for going on sure grounds, before giving up such a position as my present
one.
I considered it also my duty before writing to Massow, to communicate
the circumstance under the seal of the strictest secrecy to my friends here,
Schleinitz and David, who are quite of my opinion, that I ought to leave
this, however much they regret it, if my wishes are fulfilled with regard to a
defined position. At the same time, I purpose, in the course of a few days, to
make known to our Concert Director, and Government President, that I
have received such an offer (without naming the place), and that it is
probable I may accept it. Perhaps you may not approve of this, but I feel I
cannot act otherwise. If my negotiations with Massow were to terminate by
our agreeing, without my having given any hint of such a transaction, it
would show a want of good feeling on my part, and, indeed, in my present
circumstances, a want of common gratitude. But this is in fact a mere matter
of form, for it is not probable that they will for a moment think of entering
into competition with the recent overtures from Berlin, and yet I delay the
announcement from day to day, because such a step must be final.—Your
Felix.
To Paul Mendelssohn Bartholdy.
Leipzig, Jan. 2nd, 1841.
Dear Paul,
Receive my heartfelt good wishes, and may God grant us all a happy
new year! Now I have one earnest request to make. Do not allow any
misunderstanding between Massow and me, to impair that delightful and
perfect harmony between us which always rejoices me, and makes me so
happy. I will not say, let us not become more mistrustful, but not even more
reserved towards each other. Since the great sacrifice that you
unhesitatingly made for my sake in coming here, I confess I am in great
anxiety on this subject, and it makes me very uneasy when I think it
possible that you may be dissatisfied with me, for not being prepared to
accept your opinion at once—angry, I do not think you will be, but as I
have already said, do not permit anything whatever to be changed between
you and me,—promise me this; you know how much I have at heart our
being able to live together at some future day; but if we were only to pass a
few untroubled years together, and I were then to go on my way in
vexation, that would be worse than it is now, and I would gladly avoid this.
I tell you so, because in your letter you urge me so strongly fairly to speak
out, as if I had not in my answer to Massow already spoken out on many
points, more, perhaps, than I ought to have done. You also wish to persuade
me to go now to Berlin, but you will soon be convinced, that this winter,
such a thing is impossible. I have five subscription concerts, and three extra
concerts to direct in January, and in the beginning of March, Bach’s
“Passion,” of which not a single note is known here, and I certainly cannot
get away during the time of the concerts, without injuring them. But
independent of this, what should I do in Berlin? The statutes of a new
Academy are better arranged by writing than verbally, and from the tenor of
Massow’s letters, the affair does not seem so far advanced, as to permit of
its being definitively settled in the course of a couple of days; at least, not in
the sense that we mutually wish; so, as I said, dear Paul, promise me, never
under any circumstances, to be displeased with me.
I told Massow in a letter to-day, that I should be happy to explain my
views with regard to reorganizing the Musical Academy, either to him, or to
Eichhorn; for this purpose he has only to send me the statutes hitherto in
force, and the composition of the classes, of which I am entirely ignorant,
and also say how far the modifications are to be carried, whether to the
extent of a radical change, or merely a reform; this I must learn of course,
or I should not know what to say; I will gladly devote my time and efforts
to the mere possibility of our once more living together, but I must confess,
that since Massow’s last letter, such a possibility seems even more distant
than I myself thought. It sounds all so different from what they
commissioned you to say to me when you came here, and if it begins in
such a way, no doubt the sequel will be still worse. The salary they offer is
certainly handsome and liberal, but if they in return expect me to accept an
unlimited obligation to work, that also would be a change in their proposals,
and no compensation to me. The salary is the only point on which Massow
spoke in a decided manner to me, and my position is too fortunate for mere
money to influence my views. All that you told me here about a rota
between the different directors, and the duties of the Capellmeister of the
Royal Chapel, and of the engagement of other foreign musicians,—not a
word of this was brought forward; on the contrary, Massow writes to me,
that he is glad I have declared myself satisfied with the title and the salary,
which is totally opposed to the sense of my previous letter, in which I
expressed a wish to know my duties, before I could explain my intentions.
Indeed, even if the alteration in the musical class were to be entered into,
and carried through exactly according to my wishes, I scarcely know (as the
title is in question) whether I should quite like to go to Berlin as “Director
of the Musical Class,” which is by no means in good odour with musicians
at present. I can say all this to you without incurring the suspicion of a
fondness for titles, for what annoys me is their drawing back in all their
proposals; perhaps I am mistaken; at all events, I hope in my letter to
Massow you will find no trace of the dissatisfaction which I have frankly
expressed to you. I shall assist in establishing the new regulations as well
and as firmly as possible; in any event, good service will be done to the
cause, so far as I can accomplish it, and if the result is to be satisfactory, the
affair must first be made clear; not merely in reference to my personal
acceptance, but because it is right and desirable for the affair itself, and in
order to enable any good musician (not merely myself) to interest
themselves in it hereafter; for now the question again recurs, whether I, or
some other efficient musician shall be placed at the head, and all the other
questions become mere secondary considerations.
For Heaven’s sake! tell me, how came you to be reading that abominable
thing of Diderot’s? He was ashamed of it later in life, but the traces of his
genius are to be discovered even in this muddy pool. I may possibly feel
more mildly disposed towards him just now, because two pietistic works
were sent to me yesterday from Berlin,—so gloomy, such a perfect type of
the worst time of the priesthood, that I am almost inclined to welcome the
French with their audacity, and Voltaire with his broom. Perhaps you know
one of these? It is called “Die Passion, ein kirchliches Festspiel;” it is
written in doggerel rhymes, and is the most wretched trash I have lately
read,—Heine included. The other is a criticism written by a person on his
own oratorio, in which he exhorts the people to piety and frequent
communion, and says no one is entitled to pronounce any opinion on his
music, who does not listen to it in the spirit of true piety, and in faith. Alas!
alas!
Remember my first request in this new year, and love me as much as
ever.—Your
Felix.
To Paul Mendelssohn Bartholdy.
Leipzig, Jan. 9th, 1841.
Dear Paul,
Your letter of yesterday made me very happy; God knows why I could
not get it out of my head that you were angry with me, for delaying an affair
which you wished to expedite, and have so kindly expedited. I however see
from your letter that I was entirely and totally wrong, and I thank you much
for it, and subscribe to all you say on the subject. But there is one idea you
must dismiss from your thoughts as much as I have done the other, and that
is the dread of foreign influences, as you call them, which you allude to in
your letter. You must not suppose that I ever act in any affair but from my
own conscientious impulses, far less in a matter in which I myself and my
happiness are so very closely involved. Believe me, that in general, I
invariably strive to do and say nothing but what I hold to be right in my
conscience and instinct, and it is a proof that we have, alas! lived much
asunder, and only met in days of enjoyment, and not of work, when you
fear that I am easily swayed, not only in conversation, but in action. No! all
goes on very slowly with me, but when at last I do a foolish thing, I have at
least one merit, which is, to have devised it entirely myself. With regard to
this special case, I probably gave you cause for suspicion, by writing to you
that I told my friends here, David and Schleinitz of the offer, and in my last
letter I did not allude to them again. I can assure you, however, that both
have long ago given me such proofs of sincere friendship, that I could not
possibly have been silent to them on this occasion, and both urged my
acceptance, and saw the thing in the most favourable light.
That not the smallest step I have taken in the whole affair may be
unknown to you, I must add, that I felt myself obliged to communicate the
circumstance candidly, some days ago, to the Kreis-Director, Herr von
Falkenstein; for in this month the money becomes due which the King has
the disposal of, and which, as you are aware, I last winter petitioned might
be appropriated to found a school of music here. The King, who expressed
himself in a very kind manner towards me, when he came to one of our
subscription concerts, seemed well disposed to give his consent; then came
Falkenstein to ask me if I would pledge myself (which really was my idea
at that time) to organize this music school for some years to come. I now no
longer could or would do this, so I thought it best to tell him the whole
affair. He gave me his faithful promise to preserve the strictest silence, and I
in turn agreed to give him due notice if I settled to go to Berlin, because
that, he said, might be prejudicial to the plan of the music school; and thus
it now stands.
I await the arrival of the statutes; at all events an opportunity may then
occur to render an occasional service to the cause there, and to place many
things on a better footing, and perhaps to introduce a better system into the
whole class, and some good would be thus effected.
The examples which you quote of the advantage of public opinion
interested me very much, but I own were far from pleasing to me. I do not
call that public opinion, which is shown by sending anonymous and
libellous verses, and by hissing an old masterpiece.[45] You will perhaps say
this is only the beginning; but that is the very point; if a thing is not rightly
begun it never comes to a good end, and I do not believe that public
tracasseries can pave the way to public opinion; indeed, I believe that such
things have always existed, and always will exist, independent of the vox
populi, which is the vox Dei. It would be more important to me if you
would tell me some particulars of the curiosa which are related of Minister
Schön; pray do this if you possibly can. He seems to be a determined
fellow!—Your
Felix.
To Herr X——.
Leipzig, January 22nd, 1841.
Sir,
I beg to offer you my thanks for the confidence you have shown me by
your polite letter, and the accompanying music. I have looked over your
overture with much pleasure, and discovered many unmistakable traces of
talent in it, so that I should rejoice to have an opportunity of seeing some
more new works of yours, and thus to make your musical acquaintance in a
more intimate and confidential manner. The greater part of the
instrumentation, and especially the melodious passage which is in fact the
principal subject, pleased me much. If I were to find any fault, it would be
one with which I have often reproached myself in my own works; in the
very overtures you allude to, sometimes in a greater, and sometimes in a
lesser degree. It is often very difficult, in such fantastical airy subjects, to
hit the right medium. If you grasp it too firmly, it is apt to become formal
and prosaic; and if too delicately, it dissolves into air and melody, and does
not become a defined form. This last rock you seem to have split upon; in
many passages, especially at the very beginning, but also here and there in
other parts, and towards the close again, I feel the want of a musical well-
defined form, the outlines of which I can recognize, however misty, and
grasp and enjoy. I should like, besides the meno allegro, to see some other
more definite idea, and to have it worked out; only then, the other rock is
too apt to show itself, and modulations be seen, where there should be
nothing but moonlight. In order, however, to give free course to these
poetical thoughts, the spirit of entire supremacy must hover over the whole
(that fact should not become too dry, nor fancy too misty); and it is only
where this complete mastery over thought and arrangement exists, that the
reins may be given to imagination. This is the very point which we are all
obliged, more or less, to study; I hope you will not be offended, therefore,
that I do not find this problem entirely solved in your work either; in your
future productions, with which I hope to become acquainted, the connection
will, no doubt, be closer, and my critical remarks rendered unnecessary.—I
am, with sincere esteem, yours,
Felix Mendelssohn Bartholdy.
To his Mother.
Leipzig, January 25th, 1841.
... This is the thirty-fifth letter I have written since the day before
yesterday; it makes me quite uneasy to see how the flood swells, if a few
days elapse without my stemming it, and guarding against it. Variations
from Lausitz and Mayence; overtures from Hanover, Copenhagen,
Brunswick, and Rudolstadt; German Fatherland songs from Weimar,
Brunswick, and Berlin, the latter of which I am to set to music, and the
former to look over and take to a publisher: and all these accompanied by
such amiable, polite letters, that I should be ashamed if I were not to reply
to them in as amiable and kind a manner as I possibly can. But who can
give me back the precious days which pass away in these things? Add to
this, persons who wish to be examined, eagerly awaiting my report for their
anxious relatives, whether they are to become professional musicians or
not; two Rhenish youths are here at this moment for that purpose, and the
verdict is to be given in the course of a few hours. It is really a heavy
responsibility, and I often think of La Fontaine’s rat, who retired into a
cheese, and thence delivered oracles.
To Paul Mendelssohn Bartholdy.
Leipzig, February 13th, 1841.
My dear Brother,
It is curious how certain years elapse, when both time and people seem
to stand quietly still; and then again come weeks, when everything seems to
run about like billiard balls, making cannons, and losing and winning
hazards, etc. etc. (vide the Temperance Hotel in Gohlis). Such has been the
case with me during the last few months. Since you were here, everything is
so far advanced and altered, that it would take me a week at least, and walks
innumerable, without letting you utter a word, before I could tell you all,
and probably it has been the same with you.
The Berlin affair is much in my thoughts, and is a subject for serious
consideration. I doubt whether it will ever lead to that result which we both
(I believe) would prefer; for I still have misgivings as to Berlin being a soil
where a person of my profession could feel even tolerably at home, in spite
of all honours and money, but the mere offer in itself gives me an inward
impulse, a certain satisfaction, which is of infinite value to me, even if I
were never to speak of it to any one; in a word, I feel that an honour has
been done me, and I rejoice in it. Massow writes in his last letter, which I
received before yours, that the King wishes to delay the definitive
arrangement of the Academy till I go to Berlin in spring; whether I choose
to make proposals in writing as to the alteration of the statutes which he
sends me, he leaves entirely to my own decision. As this point is left to
myself, and I would far rather not write at all on the subject, I shall delay
doing so till I know to a certainty whether I go to Berlin in spring or not,
and only in the latter case write. Remarkable, very remarkable these statutes
are, especially those of the school for composition. Imagine! out of eleven
different branches of instruction which they have instituted, seven are
positively useless, and indeed preposterous. What do you think of the
following, among others? No. 8. “The relation Music bears to the other arts,
especially to the plastic and to the stage;” and also No. 11, “A guide to the
spiritual and worldly Drama.” I formerly read these things in the
Government paper, and laughed at them; but when a grave minister or
official actually sends such stuff, it is pitiable. Pray do go to some public
place where newspapers are collected, and send me the one which
advertises this course, and where the teachers of the different branches are
named. I require these data thoroughly to understand the affair. It is all in
the worst possible state; you will say this is the very reason why I should try
to extricate it. In that case there would indeed be plenty to do, if I could
only think myself the man to do it; to improve what is already good, or to
create what is new and good, would be an undertaking that I should rejoice
in, and which might be learned, even if there were no previous knowledge
of the subject; but to change what is positively bad into better things, is both
a hard and a thankless task.
A very momentous change has taken place here since what is called the
King’s concert. You cannot think what a good impulse the mere visit of the
King, and his really cordial and kind approbation, has imparted to our
concerts here. A person is almost to be envied who, by pure, kindly, natural
feelings, and words of the same tenor, can give such an immediate impetus,
were it not after all quite as difficult, in such a position, to preserve such
feelings (which is the main point) as it is with us to maintain many less
essential. By his demeanour here, us well as by the way in which he has
sounded forth our praises in Dresden, he has facilitated a number of things
for us which were not thought of formerly. Since that time, we have
strangers from Dresden at every concert, and the female singers there vie
with each other in their efforts to appear in public here. The grant, too, of
the legacy bequeathed two years ago, will now probably be entirely devoted
to musical purposes, and perhaps be finally decided this month. All these
are only mere outlines; but how many details I might have added during the
walks I alluded to! There has been one thing, however, and that indeed the
chief thing, which I have not been able to accomplish during all these
winter months, and that is composition. I sent my “Hymn of Praise” to be
published, and have written a couple of songs; this is however all, and little
enough too.
Now as to literature, I am but in a poor state in that respect. Last week I
had scarcely time to eat or to sleep my pensum, without being fairly
stranded, and no possibility of reading. I read Immermann’s ‘Münchhausen’
some time ago, but only the first volume; and I must confess that the first
half of it, which you too do not praise, displeased me so much, that I was
out of sorts with the second also, although I do not deny the great beauties
in the second Westphalian portion, and in all those works of his which I
have seen. I feel the same with regard to X——’s critical article. When I see
an old companion, endowed by a kind Providence with every good
capability, roaming about for many long years, employing his really fine
talents in writing for newspapers, and criticizing a book which perhaps had
better never have been written (but for the money the bookseller gave for
it), and with these exceptions bringing nothing of his own into the world,
advancing nothing and contributing nothing, I cannot help thinking that it is
the greatest blasphemy which can be committed against Providence, and so
I don’t wish to know anything of his clever criticisms, and feel a much
higher esteem for every honest bookbinder and cobbler. This is, no doubt,
one-sided, and too severe also; but I know nothing worse than the abuse, or
non-use of God’s gifts, and have no sympathy for those who trifle with
them.
Fie, for shame! what a cynical tone I have adopted; and I have not yet
thanked you for all the good and loving and kind things you say to me of
my music! But you must not estimate it so highly in contradistinction to that
of others. To deserve all your praise, it ought to be very much better; and
this I hope it will one day become. At all events, I think that the recitative,
and the middle of my “Hymn of Praise” are more fervent and spirited than
anything I have yet written. When shall we be able to sing it to you! With
this I close my letter. Write to me soon again.—Your
Felix.
To Fanny Hensel, Berlin.
Leipzig, February 14th, 1841.
Salut et Fraternité!
Have you read the wrathful letter which the Emperor of China wrote to
Lin, with a bright red pencil? Were this the fashion with us, I would write to
you to-day with a grass-green pencil, or with a sky-blue one, or with
whatever colour a pleasant pencil ought to assume, in gratitude for your
admirable epistle on my birthday. My especial thanks also for the kind and
friendly interest you have shown in the faithful Eckert; he is a sound,
practical musician, and further than this, in my opinion (to which I
sometimes adhere for twenty-four hours), no man should concern himself
about another. Whether a person be anything extraordinary, unique, etc., is
entirely a private matter. But in this world, every one ought to be honest and
useful, and he who is not so, must and ought to be abused, from the Lord
Chamberlain to the cobbler. Of all the young people whom I have had
anything to do with here, he is the most good-natured, and by far the most
inoffensive; and these are two precious qualities.
Don’t, I beg, write me anything more about your Sunday music, it is
really a sin and a shame that I have not heard it; but though I feel so
provoked at this, it is equally vexatious that you have heard none of our
truly brilliant subscription concerts. I tell you we glitter brightly—in Bengal
fire. The other day, in our last historical concert (Beethoven), Herr Schmidt
was suddenly taken ill, and could not sing to his “Ferne Geliebte” in the
“Liederkreis.” In the middle of the first part David said, “I see Madame
Devrient.” She had arrived that morning by rail, and was to return next day.
So during an interval, I went up to her, was vastly polite, and she agreed to
sing “Adelaide;” on which an old piano was carried into the orchestra from
the anteroom. This was greeted with much applause, for people suspected
that Devrient was coming. So come she did, in a shabby travelling costume,
and Leipzig bellowed and shouted without end. She took off her bonnet
before the publicum, and pointed to her black pelisse, as if to apologize for
it. I believe they are still applauding! She sang beautifully, and there was a
grand flourish of trumpets in her honour, and the audience clapped their
hands, till not a single bow of the shabby pelisse was any longer visible.
The next time we are to have a medley of Molique, Kalliwoda, and
Lipinski,—and thus, according to Franck’s witticism, we descend from
Adam to Holtei.
As to the tempi in my Psalm, all I have to say is, that the passage of the
Jordan must be kept very watery; it would have a good effect if the chorus
were to reel to and fro, that people might think they saw the waves; here we
have achieved this effect. If you do not know how to take the other tempi,
ask G—— about them. He understands that capitally in my Psalms. With
submission, allow me to suggest that the last movement be taken very slow
indeed, as it is called “Sing to the Lord for ever and ever,” and ought
therefore to last for a very long time! Forgive this dreadful joke. Adieu, dear
Fanny.—Your
Felix.
To Pastor Julius Schubring, Dessau.
Leipzig, February 27th, 1841.
Dear Schubring,
Thank you a thousand times for your friendly letter, which caused me
much pleasure, and was a most welcome birthday gift. Our correspondence
had certainly become rather threadbare, but pray don’t give up sending me
your little notes of introduction; large letters would indeed be better, but in
default of these I must be contented with little ones, and you well know that
they will always be received with joy, and those who bring them welcomed
to the best of my ability.
Now for my critical spectacles, and a reply about your Becker
“Rheinlied.” I like it very much; it is well written, and sounds joyous and
exhilarating, but (for a but must of course be uttered by every critic) the
whole poem is quite unsuitable for composition, and essentially unmusical.
I am well aware that in saying this, I rashly throw down the gauntlet both to
you, and many of my colleagues in Germany; but such is my opinion, and
the worst part of it is, that I am confirmed in it by most of the compositions
that I know. (For Heaven’s sake, let this remain a secret between us,
otherwise, as journalists publish every trifle nowadays, I may possibly be
some day conveyed across the frontiers as a Frenchman.) But, jesting apart,
I can only imagine music when I can realize the mood from which it
emanates; mere artistically correct tones to suit the rhythm of the poetry,
becoming forte when the words are vehement, and piano when they are
meek, sounding very pretty, but expressing nothing,—I never yet could
comprehend; and still such is the only music I can discover for this poem.
Neither forcible, nor effective, nor poetical, but only supplementary,
collateral, musical music. The latter, however, I do not choose to write. In
such cases, the fable of the two vases often recurs to me, who set off
together on a voyage, but in rolling to and fro one smashed his companion,
the one being made of clay and the other of iron. Besides, I consider the
poem to be neither bold nor cautious, neither enthusiastic nor stoical, but
only very positive, very practical, very suitable indeed for many at the
present day; however, I cannot even momentarily interest myself in any
object of which I can perceive the momentary nature, and from which I can
expect no durability. I am becoming philosophical; pray forgive me, and
forgive the whole diatribe, which is uncivil besides, because you composed
the song yourself. But as you have an immense majority of musicians on
your side, you will not, I think, be offended by my dissentient protestation,
but probably rather disposed to laugh at it. I could not help coming out with
what I thought.
You wish to know how I am. As well as possible. Yet if we see each
other in the course of a few weeks, you may perhaps hear the same
complaints from me that you did last year. I often thought of them since,
and laughed at them, because I was so well and so gay; but for a week past
such languor seems to creep over me, that, as I told you, I might sing the
very same old song of a year ago. I don’t know whether this arises from the
approach of spring, or the enormous quantity of music which I was engaged
in during the winter, and which has fairly exhausted me; for several years
past the two always come together. But I believe it is the latter; I have
conducted fifteen public performances since January,—enough to knock up
any man. Farewell, my dear friend.—Your
Felix Mendelssohn Bartholdy.
To Paul Mendelssohn Bartholdy.
Leipzig, March 3rd, 1841.
Dear Paul,
You gave me extreme pleasure by the brochure[46] you sent me
yesterday, and after having exulted not a little in its contents, I must now
thank you much for having forwarded it to me. I read of it in the
‘Allgemeine Zeitung,’ but had it not been for your kindness, this clever
publication would not have found its way to my room for many a day. I
have read it through twice with the deepest attention, and agree with you
that it is a most remarkable sign of the present time in Prussia, that nothing
more true, more candid, or more sober in form and style could be desired,
and that a year ago a similar pamphlet could not have appeared. In the
meanwhile, it is prohibited, and we shall soon see in how far it is merely an
individual lofty spirit expressing his views, or a spirit that has really
impressed and fired the whole community, for the great misfortune with us
has always been want of unanimity, of esprit de corps. A sorrowful feeling
oppresses me when I so surely see, or think I see, that the path lies open,
level and plain, on which the whole of Germany might receive a
development which it probably never had, except in years of war, and not
even then, because these years of war were years of violence also: a path on
which no one would lose, and all would gain in life, power, movement, and
activity; this path is likewise that of truth, and honour, and fidelity to
promises, and yet time after time it is never trodden, while new reasons are
perpetually found for avoiding it. This is most melancholy! In the meantime
it is fortunate that there are people who know how to set forth, what by far
the greater number feel, but cannot express. I should have to quote the
whole of the pamphlet, to name all the particular passages written so
entirely in consonance with the feelings of my heart; but I started up from
joy at both the little paragraphs on the Dantzic letter and Hanover, for they
came in so naturally, and quite as a matter of course; and then the glorious
close! As I said before, the next fortnight will prove, whether such a spirit
has the right on his side in these days, not merely in theory but in practice.
God grant it may be so!
If you hear anything further of your statesman[47] (I do not believe the
brochure is his, though quite in accordance with his creed), or any more
details that can be communicated to me, I beg you will not fail to do so. I
begin to interest myself very much in this man. What a glorious contrast
this work forms to all the French ones of last year that I have seen. Here is
indeed real substance, not merely subtleties; vigorous truth and inborn
dignity, not merely well-bred politeness or evasion of the laws.
But the work is prohibited! This is a humiliation, even amid all my
delight. Farewell; thank you again cordially for your kindness always.—
Your
Felix.
To Julius Rietz, Music Director at Düsseldorf,
(now capellmeister at dresden.)
Leipzig, April 23rd, 1841.
Add
Dear Rietz,
Yesterday evening we performed your overture to “Hero and Leander”
and the “Battle Song,” amid loud and universal applause, and with the
unanimous approbation of the musicians and the public. Even during the
rehearsal of the overture, towards the end in D major, I perceived in the
orchestra those smiling faces and nodding heads, which at a new piece of
yours I am so glad to see among the players; it pleased them all
uncommonly, and the audience, who yesterday sat as still as mice and never
uttered a sound, broke out at the close into very warm applause, and fully
confirmed the judgment of the others. I have had great delight in all these
rehearsals, and in the performance also; there is something so genuinely
artistic and so genuinely musical in your orchestral works, that I feel happy
at the first bar, and they captivate and interest me till the very end. But as
you persist in wishing me to place my critical spectacles on my nose, I must
tell you that there was one wish I formed in hearing both pieces: that you
may now write many works in succession. The chief reason for this I do not
require to tell you, for it lies on the surface. But I have yet another wish: I
perceive a certain spirit, especially in the overture, which I myself know
only too well, for in my opinion it caused my “Reformation Symphony”[48]
to fail, but which can be surely and infallibly banished by assiduous work
of different kinds. Just as the French, by conjuring tricks and overwrought
sentiment, endeavour to make their style harrowing and exciting, so I
believe it possible, through a natural repugnance to this style, to fall into the
other extreme, and so greatly to dread all that is piquant or sensuous, that at
last the musical idea does not remain sufficiently bold or interesting; that
instead of a tumour, there is a wasting away: it is the contrast between the
Jesuit churches, and their thousand glittering objects, and the Calvinists,
with their four white walls; true piety may exist in both, but still the right
path lies between the two. I entreat you to pardon this preaching tone, but
how is it possible to make oneself understood on such subjects? The
fundamental thoughts in your overture and my “Reformation Symphony”
(both having, in my opinion, similar qualities), are more interesting from
what they indicate, than actually interesting in themselves; of course I do
not plead for the latter quality alone (as that would lead us to the French),
nor for the first alone either; both must be united and blended. The most
important point is to make a thema, or anything of the kind which is in itself
musical, really interesting: this you well understand in your
instrumentation, with every second oboe or trumpet, and I should like to see
you steer boldly in that direction in your next works,—without, however,
injuring by the greater finish and sharpness of your musical thoughts, your
excellent foundation, or your masterly and admirably carried out details of
instrumentation, etc. As ideas cannot be either more highly finished or
sharpened, but must be taken and made use of as they come, and as a kind
Providence sends them—so work is the only thing which either I or others
can possibly desire for such an artist as yourself, and for works of art like
yours, where the only question is of any trifling deviation in their tendency.
Report to his Majesty the King of Prussia,[49] from the
Wirklich Geheimrath Herr von Massow.
Berlin, May 20th, 1841.
Your Majesty was pleased verbally to desire me to enter into
communication with Herr Felix Mendelssohn Bartholdy, in Leipzig, with a
view to summon him to Berlin, and to fix his residence there by
appointment. I therefore on the 11th of December last wrote to Herr
Mendelssohn, in accordance with your Majesty’s commands, and made the
following offer:—
That he should be appointed Director of the musical class of the
Academy of Arts, with a salary of three thousand thalers.
I also mentioned that it was your Majesty’s intention to reorganize the
musical class of the Academy, and to connect it with some existing
establishments for the development of musical cultivation, as well as with
others yet to be formed; that Herr Mendelssohn’s advice on the subject was
requested; that he was to be appointed the future head of this institute.
Further, that it was your Majesty’s pleasure a certain number of concerts (to
be hereafter fixed) were to be given every year under his direction, with the
aid of the Royal orchestra and the members of the opera, in which oratorios
especially, but also other works, such as symphonies, etc., were to be
performed. Herr Mendelssohn, in two letters addressed to me, on the 15th
December and the 2nd January, expressed his gratitude to your Majesty for
so honourable an offer, as well as his entire satisfaction with regard to the
title and the salary; he however reserved his full acceptance of the proposal,
until the duties involved in the situation offered to him in Berlin, were more
minutely detailed. The conscientiousness thus shown by Herr Mendelssohn
cannot fail to be acknowledged and respected; at the same time, he
promised to come to Berlin this spring.
The Academy of Arts being regulated by the Ministerium of the
departments of science, instruction, and medicine,—it was from this source
alone, that the wished-for copy of the rules could be obtained for Herr
Mendelssohn; as this, however, could not be immediately effected, Minister
Eichhorn resolved to discuss the whole affair himself with Herr
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookmasss.com

You might also like