diff --git a/src/bin/psql/Makefile b/src/bin/psql/Makefile
index c8eb2f95cc..b8c62a774f 100644
--- a/src/bin/psql/Makefile
+++ b/src/bin/psql/Makefile
@@ -15,11 +15,15 @@ PGAPPICON=win32
 subdir = src/bin/psql
 top_builddir = ../../..
 include $(top_builddir)/src/Makefile.global
+include $(top_builddir)/src/interfaces/libpq/Makefile.libdefs
 
 REFDOCDIR= $(top_srcdir)/doc/src/sgml/ref
 
 override CPPFLAGS := -I. -I$(srcdir) -I$(libpq_srcdir) $(CPPFLAGS)
 override LDFLAGS := -L$(top_builddir)/src/fe_utils -lpgfeutils $(libpq_pgport) $(LDFLAGS)
+ifeq ($(PORTNAME),darwin)
+    override LDFLAGS := -headerpad_max_install_names $(LDFLAGS)
+endif
 
 OBJS=	command.o common.o conditional.o copy.o crosstabview.o \
 	describe.o help.o input.o large_obj.o mainloop.o \
@@ -47,6 +51,19 @@ distprep: sql_help.h psqlscanslash.c
 
 install: all installdirs
 	$(INSTALL_PROGRAM) psql$(X) '$(DESTDIR)$(bindir)/psql$(X)'
+    ifndef NO_TEMP_INSTALL
+        ifeq ($(PORTNAME),darwin)
+            # With Apple's SIP (aka rootless mode) enabled one cannot use
+            # DYLD_LIBRARY_PATH to point the temp install's psql to the temp
+            # install's libpq to ensure the matching library is used.
+            # Therefore modify the binary's embedded shared library
+            # install name to point to the temp install's libpq.
+			install_name_tool -change \
+               '$(libdir)/lib$(NAME).$(SO_MAJOR_VERSION)$(DLSUFFIX)' \
+               '$(DESTDIR)$(libdir)/lib$(NAME).$(SO_MAJOR_VERSION)$(DLSUFFIX)' \
+               '$(DESTDIR)$(bindir)/psql$(X)' 
+        endif
+    endif
 	$(INSTALL_DATA) $(srcdir)/psqlrc.sample '$(DESTDIR)$(datadir)/psqlrc.sample'
 
 installdirs:
diff --git a/src/interfaces/libpq/Makefile b/src/interfaces/libpq/Makefile
index 0bf1e7ef04..597a046a39 100644
--- a/src/interfaces/libpq/Makefile
+++ b/src/interfaces/libpq/Makefile
@@ -15,9 +15,7 @@ include $(top_builddir)/src/Makefile.global
 
 
 # shared library parameters
-NAME= pq
-SO_MAJOR_VERSION= 5
-SO_MINOR_VERSION= $(MAJORVERSION)
+include ./Makefile.libdefs
 
 override CPPFLAGS :=  -DFRONTEND -DUNSAFE_STAT_OK -I$(srcdir) $(CPPFLAGS) -I$(top_builddir)/src/port -I$(top_srcdir)/src/port
 ifneq ($(PORTNAME), win32)
diff --git a/src/interfaces/libpq/Makefile.libdefs b/src/interfaces/libpq/Makefile.libdefs
new file mode 100644
index 0000000000..0d20387d3e
--- /dev/null
+++ b/src/interfaces/libpq/Makefile.libdefs
@@ -0,0 +1,8 @@
+# shared library parameters
+NAME= pq
+SO_MAJOR_VERSION= 5
+SO_MINOR_VERSION= $(MAJORVERSION)
+ifeq ($(PORTNAME), darwin)
+    DLSUFFIX= .dylib
+endif
+
