diff --git a/doc/src/sgml/catalogs.sgml b/doc/src/sgml/catalogs.sgml
index 1429b2d05c..a3cdbdb2ac 100644
--- a/doc/src/sgml/catalogs.sgml
+++ b/doc/src/sgml/catalogs.sgml
@@ -2387,6 +2387,16 @@ SCRAM-SHA-256$<replaceable>&lt;iteration count&gt;</replaceable>:<replaceable>&l
       <entry>If a foreign key, list of the referenced columns</entry>
      </row>
 
+     <row>
+      <entry><structfield>confreftype</structfield></entry>
+      <entry><type>char[]</type></entry>
+      <entry></entry>
+      <entry>If a foreign key, the reference semantics for each column:
+       <literal>p</literal> = plain (simple equality),
+       <literal>e</literal> = each element of referencing array must have a match
+      </entry>
+     </row>
+
      <row>
       <entry><structfield>conpfeqop</structfield></entry>
       <entry><type>oid[]</type></entry>
@@ -2428,6 +2438,12 @@ SCRAM-SHA-256$<replaceable>&lt;iteration count&gt;</replaceable>:<replaceable>&l
    </tgroup>
   </table>
 
+  <para>
+    When <structfield>confreftype</structfield> indicates array to scalar
+    foreign key reference semantics, the equality operators listed in
+    <structfield>conpfeqop</structfield> etc are for the array's element type.
+  </para>
+ 
   <para>
    In the case of an exclusion constraint, <structfield>conkey</structfield>
    is only useful for constraint elements that are simple column references.
diff --git a/doc/src/sgml/ddl.sgml b/doc/src/sgml/ddl.sgml
index 88a6702480..5cdf15ab3c 100644
--- a/doc/src/sgml/ddl.sgml
+++ b/doc/src/sgml/ddl.sgml
@@ -1079,6 +1079,116 @@ CREATE TABLE order_items (
    </para>
   </sect2>
 
+  <sect2 id="ddl-constraints-element-fk">
+   <title>Array Element Foreign Keys</title>
+
+   <indexterm>
+    <primary>Array Element Foreign Keys</primary>
+   </indexterm>
+
+   <indexterm>
+    <primary>ELEMENT foreign key</primary>
+   </indexterm>
+
+   <indexterm>
+    <primary>constraint</primary>
+    <secondary>Array ELEMENT foreign key</secondary>
+   </indexterm>
+
+   <indexterm>
+    <primary>constraint</primary>
+    <secondary>ELEMENT foreign key</secondary>
+   </indexterm>
+
+   <indexterm>
+    <primary>referential integrity</primary>
+   </indexterm>
+
+   <para>
+    Another option you have with foreign keys is to use a referencing column
+    which is an array of elements with the same type (or a compatible one) as
+    the referenced column in the related table. This feature is called
+    <firstterm>Array Element Foreign Keys</firstterm> and is implemented in PostgreSQL
+    with <firstterm>EACH ELEMENT OF foreign key constraints</firstterm>, as
+    described in the following example:
+
+    <programlisting>
+     CREATE TABLE drivers (
+         driver_id integer PRIMARY KEY,
+         first_name text,
+         last_name text
+     );
+
+     CREATE TABLE races (
+         race_id integer PRIMARY KEY,
+         title text,
+         race_day date,
+         final_positions integer[],
+         FOREIGN KEY <emphasis> (EACH ELEMENT OF final_positions) REFERENCES drivers </emphasis>
+     );
+    </programlisting>
+
+    The above example uses an array (<literal>final_positions</literal>) to
+    store the results of a race: for each of its elements a referential
+    integrity check is enforced on the <literal>drivers</literal> table. Note
+    that <literal>(EACH ELEMENT OF ...) REFERENCES</literal> is an extension of
+    PostgreSQL and it is not included in the SQL standard.
+   </para>
+
+   <para>
+    We currently only support the table constraint form.
+   </para>
+
+   <para>
+    Even though the most common use case for Array Element Foreign Keys constraint is on
+    a single column key, you can define a Array Element Foreign Keys constraint on a
+    group of columns.
+
+    <programlisting>
+     CREATE TABLE available_moves (
+         kind text,
+         move text,
+         description text,
+         PRIMARY KEY (kind, move)
+     );
+
+     CREATE TABLE paths (
+         description text,
+         kind text,
+         moves text[],
+         <emphasis>FOREIGN KEY (kind, EACH ELEMENT OF moves) REFERENCES available_moves (kind, move)</emphasis>
+     );
+
+     INSERT INTO available_moves VALUES ('relative', 'LN', 'look north');
+     INSERT INTO available_moves VALUES ('relative', 'RL', 'rotate left');
+     INSERT INTO available_moves VALUES ('relative', 'RR', 'rotate right');
+     INSERT INTO available_moves VALUES ('relative', 'MF', 'move forward');
+     INSERT INTO available_moves VALUES ('absolute', 'N', 'move north');
+     INSERT INTO available_moves VALUES ('absolute', 'S', 'move south');
+     INSERT INTO available_moves VALUES ('absolute', 'E', 'move east');
+     INSERT INTO available_moves VALUES ('absolute', 'W', 'move west');
+
+     INSERT INTO paths VALUES ('L-shaped path', 'relative', '{LN, RL, MF, RR, MF, MF}');
+     INSERT INTO paths VALUES ('L-shaped path', 'absolute', '{W, N, N}');
+    </programlisting>
+
+    On top of standard foreign key requirements, array
+    <literal>ELEMENT</literal> foreign key constraints require that the
+    referencing column is an array of a compatible type of the corresponding
+    referenced column.
+   
+    However, it is very important to note that, currently, we only support
+    one array reference per foreign key.
+   </para>
+
+   <para>
+    For more detailed information on Array Element Foreign Keys options and special
+    cases, please refer to the documentation for 
+    <xref linkend="sql-createtable-foreign-key"/> and
+    <xref linkend="sql-createtable-element-foreign-key-constraints"/>.
+   </para>
+  </sect2>
+
   <sect2 id="ddl-constraints-exclusion">
    <title>Exclusion Constraints</title>
 
diff --git a/doc/src/sgml/ref/create_table.sgml b/doc/src/sgml/ref/create_table.sgml
index c70d2ed7c9..cbc4f7f656 100644
--- a/doc/src/sgml/ref/create_table.sgml
+++ b/doc/src/sgml/ref/create_table.sgml
@@ -1019,10 +1019,10 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM
     </listitem>
    </varlistentry>
 
-   <varlistentry>
+   <varlistentry id="sql-createtable-foreign-key" xreflabel="FOREIGN KEY">
     <term><literal>REFERENCES <replaceable class="parameter">reftable</replaceable> [ ( <replaceable class="parameter">refcolumn</replaceable> ) ] [ MATCH <replaceable class="parameter">matchtype</replaceable> ] [ ON DELETE <replaceable class="parameter">referential_action</replaceable> ] [ ON UPDATE <replaceable class="parameter">referential_action</replaceable> ]</literal> (column constraint)</term>
 
-   <term><literal>FOREIGN KEY ( <replaceable class="parameter">column_name</replaceable> [, ... ] )
+   <term><literal>FOREIGN KEY ( [EACH ELEMENT OF] <replaceable class="parameter">column_name</replaceable> [, ... ] )
     REFERENCES <replaceable class="parameter">reftable</replaceable> [ ( <replaceable class="parameter">refcolumn</replaceable> [, ... ] ) ]
     [ MATCH <replaceable class="parameter">matchtype</replaceable> ]
     [ ON DELETE <replaceable class="parameter">referential_action</replaceable> ]
@@ -1047,6 +1047,18 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM
       tables and permanent tables.
      </para>
 
+     <para>
+      In case the column name <replaceable class="parameter">column</replaceable> is 
+      prepended with the <literal>EACH ELEMENT OF</literal> keyword and <replaceable 
+      class="parameter">column</replaceable> is an array of elements compatible with 
+      the corresponding <replaceable class="parameter">refcolumn</replaceable> in 
+      <replaceable class="parameter">reftable</replaceable>, an Array Element Foreign Key 
+      constraint is put in place (see <xref 
+      linkend="sql-createtable-element-foreign-key-constraints"/> for more 
+      information). Multi-column keys with more than one <literal>EACH ELEMENT 
+      OF</literal> column are currently not allowed. 
+     </para>
+
      <para>
       A value inserted into the referencing column(s) is matched against the
       values of the referenced table and referenced columns using the
@@ -1110,7 +1122,8 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM
          <para>
           Delete any rows referencing the deleted row, or update the
           values of the referencing column(s) to the new values of the
-          referenced columns, respectively.
+          referenced columns, respectively. 
+          Currently not supported with Array Element Foreign Keys.
          </para>
         </listitem>
        </varlistentry>
@@ -1120,6 +1133,7 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM
         <listitem>
          <para>
           Set the referencing column(s) to null.
+          Currently not supported with Array Element Foreign Keys.
          </para>
         </listitem>
        </varlistentry>
@@ -1131,6 +1145,7 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM
           Set the referencing column(s) to their default values.
           (There must be a row in the referenced table matching the default
           values, if they are not null, or the operation will fail.)
+          Currently not supported with Array Element Foreign Keys.
          </para>
         </listitem>
        </varlistentry>
@@ -1146,6 +1161,73 @@ WITH ( MODULUS <replaceable class="parameter">numeric_literal</replaceable>, REM
     </listitem>
    </varlistentry>
 
+   <varlistentry id="sql-createtable-element-foreign-key-constraints" xreflabel="Array ELEMENT Foreign Keys">
+    <term><literal>EACH ELEMENT OF <replaceable class="parameter">reftable</replaceable> [ ( <replaceable class="parameter">refcolumn</replaceable> ) ] [ MATCH <replaceable class="parameter">matchtype</replaceable> ] [ ON DELETE <replaceable class="parameter">action</replaceable> ] [ ON UPDATE <replaceable class="parameter">action</replaceable> ]</literal> (column constraint)</term>
+
+    <listitem>
+     <para>
+      The <literal>EACH ELEMENT OF REFERENCES</literal> definition specifies a 
+      <quote>Array Element Foreign Key</quote>, a special kind of foreign key constraint 
+      requiring the referencing column to be an array of elements of the same type (or 
+      a compatible one) as the referenced column in the referenced table. The value of 
+      each element of the <replaceable class="parameter">refcolumn</replaceable> array 
+      will be matched against some row of <replaceable 
+      class="parameter">reftable</replaceable>. 
+     </para>
+
+     <para>
+      Array Element Foreign Keys are an extension of PostgreSQL and are not included in the SQL standard.
+     </para>
+
+     <para>
+      Even with Array Element Foreign Keys, modifications in the referenced column can trigger 
+      actions to be performed on the referencing array. Similarly to standard foreign 
+      keys, you can specify these actions using the <literal>ON DELETE</literal> and 
+      <literal>ON UPDATE</literal> clauses. However, only the following actions for 
+      each clause are currently allowed:
+
+      <variablelist>
+       <varlistentry>
+        <term><literal>ON UPDATE/DELETE NO ACTION</literal></term>
+        <listitem>
+         <para>
+          Same as standard foreign key constraints. This is the default action.
+         </para>
+        </listitem>
+       </varlistentry>
+
+       <varlistentry>
+        <term><literal>ON UPDATE/DELETE RESTRICT</literal></term>
+        <listitem>
+         <para>
+          Same as standard foreign key constraints.
+         </para>
+        </listitem>
+       </varlistentry>
+      </variablelist>
+     </para>
+
+     <para>
+      It is advisable to index the refrencing column using GIN index as it 
+      considerably enhances the performance. Also concerning coercion while using the 
+      GIN index:
+        
+      <programlisting>
+       CREATE TABLE pktableforarray ( ptest1 int2 PRIMARY KEY, ptest2 text );
+       CREATE TABLE fktableforarray ( ftest1 int4[], FOREIGN KEY (EACH ELEMENT OF ftest1) REFERENCES PKTABLEFORARRAY, ftest2 int );
+      </programlisting>
+      This syntax is fine since it will cast ptest1 to int4 upon RI checks,        
+
+      <programlisting>
+       CREATE TABLE pktableforarray ( ptest1 int4 PRIMARY KEY, ptest2 text );
+       CREATE TABLE fktableforarray ( ftest1 int2[], FOREIGN KEY (EACH ELEMENT OF ftest1) REFERENCES PKTABLEFORARRAY, ftest2 int );        
+      </programlisting>
+       however, this syntax will cast ftest1 to int4 upon RI checks, thus defeating the
+       purpose of the index.
+     </para>
+    </listitem>
+   </varlistentry>
+
    <varlistentry>
     <term><literal>DEFERRABLE</literal></term>
     <term><literal>NOT DEFERRABLE</literal></term>
@@ -2264,6 +2346,15 @@ CREATE TABLE cities_partdef
    </para>
   </refsect2>
 
+  <refsect2>
+   <title id="sql-createtable-foreign-key-arrays">Array <literal>ELEMENT</literal> Foreign Keys</title>
+
+   <para>
+    Array <literal>ELEMENT</literal> Foreign Keys and the <literal>EACH ELEMENT 
+    OF</literal> clause are a <productname>PostgreSQL</productname> extension. 
+   </para>
+  </refsect2>
+
   <refsect2>
    <title><literal>PARTITION BY</literal> Clause</title>
 
diff --git a/src/backend/catalog/heap.c b/src/backend/catalog/heap.c
index 46a383294e..c8c85ab725 100644
--- a/src/backend/catalog/heap.c
+++ b/src/backend/catalog/heap.c
@@ -2432,6 +2432,7 @@ StoreRelCheck(Relation rel, const char *ccname, Node *expr,
 							  NULL,
 							  NULL,
 							  NULL,
+							  NULL,
 							  0,
 							  ' ',
 							  ' ',
diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c
index 5b2507cd29..0d1d8196a0 100644
--- a/src/backend/catalog/index.c
+++ b/src/backend/catalog/index.c
@@ -1886,6 +1886,7 @@ index_constraint_create(Relation heapRelation,
 								   NULL,
 								   NULL,
 								   NULL,
+								   NULL,
 								   0,
 								   ' ',
 								   ' ',
diff --git a/src/backend/catalog/pg_constraint.c b/src/backend/catalog/pg_constraint.c
index b6145593a3..178fe8183a 100644
--- a/src/backend/catalog/pg_constraint.c
+++ b/src/backend/catalog/pg_constraint.c
@@ -63,6 +63,7 @@ CreateConstraintEntry(const char *constraintName,
 					  Oid indexRelId,
 					  Oid foreignRelId,
 					  const int16 *foreignKey,
+					  const char *foreignRefType,
 					  const Oid *pfEqOp,
 					  const Oid *ppEqOp,
 					  const Oid *ffEqOp,
@@ -85,6 +86,7 @@ CreateConstraintEntry(const char *constraintName,
 	Datum		values[Natts_pg_constraint];
 	ArrayType  *conkeyArray;
 	ArrayType  *confkeyArray;
+	ArrayType  *confreftypeArray;
 	ArrayType  *conpfeqopArray;
 	ArrayType  *conppeqopArray;
 	ArrayType  *conffeqopArray;
@@ -122,7 +124,11 @@ CreateConstraintEntry(const char *constraintName,
 		for (i = 0; i < foreignNKeys; i++)
 			fkdatums[i] = Int16GetDatum(foreignKey[i]);
 		confkeyArray = construct_array(fkdatums, foreignNKeys,
-									   INT2OID, 2, true, 's');
+									   INT2OID, sizeof(int16), true, 's');
+		for (i = 0; i < foreignNKeys; i++)
+			fkdatums[i] = CharGetDatum(foreignRefType[i]);
+		confreftypeArray = construct_array(fkdatums, foreignNKeys,
+										   CHAROID, sizeof(char), true, 'c');
 		for (i = 0; i < foreignNKeys; i++)
 			fkdatums[i] = ObjectIdGetDatum(pfEqOp[i]);
 		conpfeqopArray = construct_array(fkdatums, foreignNKeys,
@@ -139,6 +145,7 @@ CreateConstraintEntry(const char *constraintName,
 	else
 	{
 		confkeyArray = NULL;
+		confreftypeArray = NULL;
 		conpfeqopArray = NULL;
 		conppeqopArray = NULL;
 		conffeqopArray = NULL;
@@ -195,6 +202,11 @@ CreateConstraintEntry(const char *constraintName,
 	else
 		nulls[Anum_pg_constraint_confkey - 1] = true;
 
+	if (confreftypeArray)
+		values[Anum_pg_constraint_confreftype - 1] = PointerGetDatum(confreftypeArray);
+	else
+		nulls[Anum_pg_constraint_confreftype - 1] = true;
+
 	if (conpfeqopArray)
 		values[Anum_pg_constraint_conpfeqop - 1] = PointerGetDatum(conpfeqopArray);
 	else
@@ -1164,7 +1176,8 @@ get_primary_key_attnos(Oid relid, bool deferrableOk, Oid *constraintOid)
 void
 DeconstructFkConstraintRow(HeapTuple tuple, int *numfks,
 						   AttrNumber *conkey, AttrNumber *confkey,
-						   Oid *pf_eq_oprs, Oid *pp_eq_oprs, Oid *ff_eq_oprs)
+						   Oid *pf_eq_oprs, Oid *pp_eq_oprs, Oid *ff_eq_oprs,
+						   char *fk_reftypes)
 {
 	Oid			constrId;
 	Datum		adatum;
@@ -1209,6 +1222,23 @@ DeconstructFkConstraintRow(HeapTuple tuple, int *numfks,
 	if ((Pointer) arr != DatumGetPointer(adatum))
 		pfree(arr);				/* free de-toasted copy, if any */
 
+	if (fk_reftypes)
+	{
+		adatum = SysCacheGetAttr(CONSTROID, tuple,
+								 Anum_pg_constraint_confreftype, &isNull);
+		if (isNull)
+			elog(ERROR, "null confreftype for constraint %u", constrId);
+		arr = DatumGetArrayTypeP(adatum);	/* ensure not toasted */
+		if (ARR_NDIM(arr) != 1 ||
+			ARR_DIMS(arr)[0] != numkeys ||
+			ARR_HASNULL(arr) ||
+			ARR_ELEMTYPE(arr) != CHAROID)
+			elog(ERROR, "confreftype is not a 1-D char array");
+		memcpy(fk_reftypes, ARR_DATA_PTR(arr), numkeys * sizeof(char));
+		if ((Pointer) arr != DatumGetPointer(adatum))
+			pfree(arr);				/* free de-toasted copy, if any */
+	}
+
 	if (pf_eq_oprs)
 	{
 		adatum = SysCacheGetAttr(CONSTROID, tuple,
diff --git a/src/backend/commands/matview.c b/src/backend/commands/matview.c
index 537d0e8cef..613e5527b9 100644
--- a/src/backend/commands/matview.c
+++ b/src/backend/commands/matview.c
@@ -757,7 +757,8 @@ refresh_by_match_merge(Oid matviewOid, Oid tempOid, Oid relowner,
 				generate_operator_clause(&querybuf,
 										 leftop, attrtype,
 										 op,
-										 rightop, attrtype);
+										 rightop, attrtype,
+										 FKCONSTR_REF_PLAIN);
 
 				foundUniqueIndex = true;
 			}
diff --git a/src/backend/commands/tablecmds.c b/src/backend/commands/tablecmds.c
index 6f4a3e70a4..178127bcb2 100644
--- a/src/backend/commands/tablecmds.c
+++ b/src/backend/commands/tablecmds.c
@@ -429,12 +429,12 @@ static ObjectAddress ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *
 											   LOCKMODE lockmode);
 static ObjectAddress addFkRecurseReferenced(List **wqueue, Constraint *fkconstraint,
 											Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
-											int numfks, int16 *pkattnum, int16 *fkattnum,
+											int numfks, int16 *pkattnum, int16 *fkattnum, char *fkreftypes,
 											Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
 											bool old_check_ok);
-static void addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint,
-									Relation rel, Relation pkrel, Oid indexOid, Oid parentConstr,
-									int numfks, int16 *pkattnum, int16 *fkattnum,
+static void addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint, Relation rel,
+									Relation pkrel, Oid indexOid, Oid parentConstr,
+									int numfks, int16 *pkattnum, int16 *fkattnum, char *fkreftypes,
 									Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
 									bool old_check_ok, LOCKMODE lockmode);
 static void CloneForeignKeyConstraints(List **wqueue, Relation parentRel,
@@ -7904,6 +7904,7 @@ ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
 	Relation	pkrel;
 	int16		pkattnum[INDEX_MAX_KEYS];
 	int16		fkattnum[INDEX_MAX_KEYS];
+	char		fkreftypes[INDEX_MAX_KEYS];
 	Oid			pktypoid[INDEX_MAX_KEYS];
 	Oid			fktypoid[INDEX_MAX_KEYS];
 	Oid			opclasses[INDEX_MAX_KEYS];
@@ -7911,9 +7912,11 @@ ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
 	Oid			ppeqoperators[INDEX_MAX_KEYS];
 	Oid			ffeqoperators[INDEX_MAX_KEYS];
 	int			i;
+	ListCell   *lc;
 	int			numfks,
 				numpks;
 	Oid			indexOid;
+	bool		has_array;
 	bool		old_check_ok;
 	ObjectAddress address;
 	ListCell   *old_pfeqop_item = list_head(fkconstraint->old_conpfeqop);
@@ -8002,6 +8005,7 @@ ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
 	 */
 	MemSet(pkattnum, 0, sizeof(pkattnum));
 	MemSet(fkattnum, 0, sizeof(fkattnum));
+	MemSet(fkreftypes, 0, sizeof(fkreftypes));
 	MemSet(pktypoid, 0, sizeof(pktypoid));
 	MemSet(fktypoid, 0, sizeof(fktypoid));
 	MemSet(opclasses, 0, sizeof(opclasses));
@@ -8013,6 +8017,53 @@ ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
 									 fkconstraint->fk_attrs,
 									 fkattnum, fktypoid);
 
+	/*
+	 * Validate the reference semantics codes, too, and convert list to array
+	 * format to pass to CreateConstraintEntry.
+	 */
+	Assert(list_length(fkconstraint->fk_reftypes) == numfks);
+	has_array = false;
+	i = 0;
+	foreach(lc, fkconstraint->fk_reftypes)
+	{
+		char		reftype = lfirst_int(lc);
+
+		switch (reftype)
+		{
+			case FKCONSTR_REF_PLAIN:
+				/* OK, nothing to do */
+				break;
+			case FKCONSTR_REF_EACH_ELEMENT:
+				/* At most one FK column can be an array reference */
+				if (has_array)
+					ereport(ERROR,
+							(errcode(ERRCODE_INVALID_FOREIGN_KEY),
+							 errmsg("foreign keys support only one array column")));
+				has_array = true;
+				break;
+			default:
+				elog(ERROR, "invalid fk_reftype: %d", (int) reftype);
+				break;
+		}
+		fkreftypes[i] = reftype;
+		i++;
+	}
+
+	/*
+	 * Array foreign keys support only UPDATE/DELETE NO ACTION, UPDATE/DELETE
+	 * RESTRICT amd DELETE CASCADE actions
+	 */
+	if (has_array)
+	{
+		if ((fkconstraint->fk_upd_action != FKCONSTR_ACTION_NOACTION &&
+			 fkconstraint->fk_upd_action != FKCONSTR_ACTION_RESTRICT) ||
+			(fkconstraint->fk_del_action != FKCONSTR_ACTION_NOACTION &&
+			 fkconstraint->fk_del_action != FKCONSTR_ACTION_RESTRICT))
+			ereport(ERROR,
+					(errcode(ERRCODE_INVALID_FOREIGN_KEY),
+					 errmsg("Array Element Foreign Keys support only NO ACTION and RESTRICT actions")));
+	}
+
 	/*
 	 * If the attribute list for the referenced table was omitted, lookup the
 	 * definition of the primary key and use it.  Otherwise, validate the
@@ -8126,6 +8177,65 @@ ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
 			elog(ERROR, "only b-tree indexes are supported for foreign keys");
 		eqstrategy = BTEqualStrategyNumber;
 
+		/*
+		 * If this is an array foreign key, we must look up the operators for
+		 * the array element type, not the array type itself.
+		 */
+		if (fkreftypes[i] == FKCONSTR_REF_EACH_ELEMENT)
+		{
+			Oid			elemopclass;
+
+			/* We check if the array element type exists and is of valid Oid */
+			fktype = get_base_element_type(fktype);
+			if (!OidIsValid(fktype))
+				ereport(ERROR,
+						(errcode(ERRCODE_INVALID_FOREIGN_KEY),
+						 errmsg("foreign key constraint \"%s\" cannot be implemented",
+								fkconstraint->conname),
+						 errdetail("Key column \"%s\" has type %s which is not an array type.",
+								   strVal(list_nth(fkconstraint->fk_attrs, i)),
+								   format_type_be(fktypoid[i]))));
+
+			/*
+			 * For the moment, we must also insist that the array's element
+			 * type have a default btree opclass that is in the index's
+			 * opfamily.  This is necessary because ri_triggers.c relies on
+			 * COUNT(DISTINCT x) on the element type, as well as on array_eq()
+			 * on the array type, and we need those operations to have the
+			 * same notion of equality that we're using otherwise.
+			 *
+			 * XXX this restriction is pretty annoying, considering the effort
+			 * that's been put into the rest of the RI mechanisms to make them
+			 * work with nondefault equality operators.  In particular, it
+			 * means that the cast-to-PK-datatype code path isn't useful for
+			 * array-to-scalar references.
+			 */
+			elemopclass = GetDefaultOpClass(fktype, BTREE_AM_OID);
+			if (!OidIsValid(elemopclass) ||
+				get_opclass_family(elemopclass) != opfamily)
+			{
+				/* Get the index opclass's name for the error message. */
+				char	   *opcname;
+
+				cla_ht = SearchSysCache1(CLAOID,
+										 ObjectIdGetDatum(opclasses[i]));
+				if (!HeapTupleIsValid(cla_ht))
+					elog(ERROR, "cache lookup failed for opclass %u",
+						 opclasses[i]);
+				cla_tup = (Form_pg_opclass) GETSTRUCT(cla_ht);
+				opcname = pstrdup(NameStr(cla_tup->opcname));
+				ReleaseSysCache(cla_ht);
+				ereport(ERROR,
+						(errcode(ERRCODE_DATATYPE_MISMATCH),
+						 errmsg("foreign key constraint \"%s\" cannot be implemented",
+								fkconstraint->conname),
+						 errdetail("Key column \"%s\" has element type %s which does not have a default btree operator class that's compatible with class \"%s\".",
+								   strVal(list_nth(fkconstraint->fk_attrs, i)),
+								   format_type_be(fktype),
+								   opcname)));
+			}
+		}
+
 		/*
 		 * There had better be a primary equality operator for the index.
 		 * We'll use it for PK = PK comparisons.
@@ -8224,6 +8334,13 @@ ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
 			 * We may assume that pg_constraint.conkey is not changing.
 			 */
 			old_fktype = attr->atttypid;
+			if (fkreftypes[i] == FKCONSTR_REF_EACH_ELEMENT)
+			{
+				old_fktype = get_base_element_type(old_fktype);
+				/* this shouldn't happen ... */
+				if (!OidIsValid(old_fktype))
+					elog(ERROR, "old foreign key column is not an array");
+			}
 			new_fktype = fktype;
 			old_pathtype = findFkeyCast(pfeqop_right, old_fktype,
 										&old_castfunc);
@@ -8283,6 +8400,7 @@ ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
 									 numfks,
 									 pkattnum,
 									 fkattnum,
+									 fkreftypes,
 									 pfeqoperators,
 									 ppeqoperators,
 									 ffeqoperators,
@@ -8295,6 +8413,7 @@ ATAddForeignKeyConstraint(List **wqueue, AlteredTableInfo *tab, Relation rel,
 							numfks,
 							pkattnum,
 							fkattnum,
+							fkreftypes,
 							pfeqoperators,
 							ppeqoperators,
 							ffeqoperators,
@@ -8338,7 +8457,7 @@ static ObjectAddress
 addFkRecurseReferenced(List **wqueue, Constraint *fkconstraint, Relation rel,
 					   Relation pkrel, Oid indexOid, Oid parentConstr,
 					   int numfks,
-					   int16 *pkattnum, int16 *fkattnum, Oid *pfeqoperators,
+					   int16 *pkattnum, int16 *fkattnum, char *fkreftypes, Oid *pfeqoperators,
 					   Oid *ppeqoperators, Oid *ffeqoperators, bool old_check_ok)
 {
 	ObjectAddress address;
@@ -8408,6 +8527,7 @@ addFkRecurseReferenced(List **wqueue, Constraint *fkconstraint, Relation rel,
 									  indexOid,
 									  RelationGetRelid(pkrel),
 									  pkattnum,
+									  fkreftypes,
 									  pfeqoperators,
 									  ppeqoperators,
 									  ffeqoperators,
@@ -8494,7 +8614,7 @@ addFkRecurseReferenced(List **wqueue, Constraint *fkconstraint, Relation rel,
 					 indexOid, RelationGetRelationName(partRel));
 			addFkRecurseReferenced(wqueue, fkconstraint, rel, partRel,
 								   partIndexId, constrOid, numfks,
-								   mapped_pkattnum, fkattnum,
+								   mapped_pkattnum, fkattnum, fkreftypes,
 								   pfeqoperators, ppeqoperators, ffeqoperators,
 								   old_check_ok);
 
@@ -8543,7 +8663,7 @@ addFkRecurseReferenced(List **wqueue, Constraint *fkconstraint, Relation rel,
 static void
 addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint, Relation rel,
 						Relation pkrel, Oid indexOid, Oid parentConstr,
-						int numfks, int16 *pkattnum, int16 *fkattnum,
+						int numfks, int16 *pkattnum, int16 *fkattnum, char *fkreftypes,
 						Oid *pfeqoperators, Oid *ppeqoperators, Oid *ffeqoperators,
 						bool old_check_ok, LOCKMODE lockmode)
 {
@@ -8678,6 +8798,7 @@ addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint, Relation rel,
 									  indexOid,
 									  RelationGetRelid(pkrel),
 									  pkattnum,
+									  fkreftypes,
 									  pfeqoperators,
 									  ppeqoperators,
 									  ffeqoperators,
@@ -8713,6 +8834,7 @@ addFkRecurseReferencing(List **wqueue, Constraint *fkconstraint, Relation rel,
 									numfks,
 									pkattnum,
 									mapped_fkattnum,
+									fkreftypes,
 									pfeqoperators,
 									ppeqoperators,
 									ffeqoperators,
@@ -8822,6 +8944,7 @@ CloneFkReferenced(Relation parentRel, Relation partitionRel)
 		Oid			conpfeqop[INDEX_MAX_KEYS];
 		Oid			conppeqop[INDEX_MAX_KEYS];
 		Oid			conffeqop[INDEX_MAX_KEYS];
+		char		confreftype[INDEX_MAX_KEYS];
 		Constraint *fkconstraint;
 
 		tuple = SearchSysCache1(CONSTROID, constrOid);
@@ -8854,7 +8977,8 @@ CloneFkReferenced(Relation parentRel, Relation partitionRel)
 								   confkey,
 								   conpfeqop,
 								   conppeqop,
-								   conffeqop);
+								   conffeqop,
+								   confreftype);
 		for (int i = 0; i < numfks; i++)
 			mapped_confkey[i] = attmap[confkey[i] - 1];
 
@@ -8897,6 +9021,7 @@ CloneFkReferenced(Relation parentRel, Relation partitionRel)
 							   numfks,
 							   mapped_confkey,
 							   conkey,
+							   confreftype,
 							   conpfeqop,
 							   conppeqop,
 							   conffeqop,
@@ -8968,6 +9093,7 @@ CloneFkReferencing(List **wqueue, Relation parentRel, Relation partRel)
 		AttrNumber	conkey[INDEX_MAX_KEYS];
 		AttrNumber	mapped_conkey[INDEX_MAX_KEYS];
 		AttrNumber	confkey[INDEX_MAX_KEYS];
+		char		confreftype[INDEX_MAX_KEYS];
 		Oid			conpfeqop[INDEX_MAX_KEYS];
 		Oid			conppeqop[INDEX_MAX_KEYS];
 		Oid			conffeqop[INDEX_MAX_KEYS];
@@ -9002,7 +9128,8 @@ CloneFkReferencing(List **wqueue, Relation parentRel, Relation partRel)
 									   ShareRowExclusiveLock, NULL);
 
 		DeconstructFkConstraintRow(tuple, &numfks, conkey, confkey,
-								   conpfeqop, conppeqop, conffeqop);
+								   conpfeqop, conppeqop, conffeqop,
+								   confreftype);
 		for (int i = 0; i < numfks; i++)
 			mapped_conkey[i] = attmap[conkey[i] - 1];
 
@@ -9081,6 +9208,7 @@ CloneFkReferencing(List **wqueue, Relation parentRel, Relation partRel)
 								  indexOid,
 								  constrForm->confrelid,	/* same foreign rel */
 								  confkey,
+								  confreftype,
 								  conpfeqop,
 								  conppeqop,
 								  conffeqop,
@@ -9119,6 +9247,7 @@ CloneFkReferencing(List **wqueue, Relation parentRel, Relation partRel)
 								numfks,
 								confkey,
 								mapped_conkey,
+								confreftype,
 								conpfeqop,
 								conppeqop,
 								conffeqop,
diff --git a/src/backend/commands/trigger.c b/src/backend/commands/trigger.c
index 5d26f998fa..111eb240c9 100644
--- a/src/backend/commands/trigger.c
+++ b/src/backend/commands/trigger.c
@@ -766,6 +766,7 @@ CreateTrigger(CreateTrigStmt *stmt, const char *queryString,
 											  NULL,
 											  NULL,
 											  NULL,
+											  NULL,
 											  0,
 											  ' ',
 											  ' ',
@@ -1256,6 +1257,7 @@ ConvertTriggerToFK(CreateTrigStmt *stmt, Oid funcoid)
 	char		fk_matchtype = FKCONSTR_MATCH_SIMPLE;
 	List	   *fk_attrs = NIL;
 	List	   *pk_attrs = NIL;
+	List	   *fk_reftypes = NIL;
 	StringInfoData buf;
 	int			funcnum;
 	OldTriggerInfo *info = NULL;
@@ -1285,7 +1287,10 @@ ConvertTriggerToFK(CreateTrigStmt *stmt, Oid funcoid)
 		if (i % 2)
 			fk_attrs = lappend(fk_attrs, arg);
 		else
+		{
 			pk_attrs = lappend(pk_attrs, arg);
+			fk_reftypes = lappend_int(fk_reftypes, FKCONSTR_REF_PLAIN);
+		}
 	}
 
 	/* Prepare description of constraint for use in messages */
@@ -1424,6 +1429,7 @@ ConvertTriggerToFK(CreateTrigStmt *stmt, Oid funcoid)
 			fkcon->conname = constr_name;
 		fkcon->fk_attrs = fk_attrs;
 		fkcon->pk_attrs = pk_attrs;
+		fkcon->fk_reftypes = fk_reftypes;
 		fkcon->fk_matchtype = fk_matchtype;
 		switch (info->funcoids[0])
 		{
diff --git a/src/backend/commands/typecmds.c b/src/backend/commands/typecmds.c
index 320f1c5285..595b7b841f 100644
--- a/src/backend/commands/typecmds.c
+++ b/src/backend/commands/typecmds.c
@@ -3189,6 +3189,7 @@ domainAddConstraint(Oid domainOid, Oid domainNamespace, Oid baseTypeOid,
 							  NULL,
 							  NULL,
 							  NULL,
+							  NULL,
 							  0,
 							  ' ',
 							  ' ',
diff --git a/src/backend/nodes/copyfuncs.c b/src/backend/nodes/copyfuncs.c
index a0ef3ff140..30d2cd0018 100644
--- a/src/backend/nodes/copyfuncs.c
+++ b/src/backend/nodes/copyfuncs.c
@@ -2926,6 +2926,7 @@ _copyConstraint(const Constraint *from)
 	COPY_NODE_FIELD(pktable);
 	COPY_NODE_FIELD(fk_attrs);
 	COPY_NODE_FIELD(pk_attrs);
+	COPY_NODE_FIELD(fk_reftypes);
 	COPY_SCALAR_FIELD(fk_matchtype);
 	COPY_SCALAR_FIELD(fk_upd_action);
 	COPY_SCALAR_FIELD(fk_del_action);
diff --git a/src/backend/nodes/equalfuncs.c b/src/backend/nodes/equalfuncs.c
index 88e17a3a60..74cdd42b22 100644
--- a/src/backend/nodes/equalfuncs.c
+++ b/src/backend/nodes/equalfuncs.c
@@ -2601,6 +2601,7 @@ _equalConstraint(const Constraint *a, const Constraint *b)
 	COMPARE_NODE_FIELD(pktable);
 	COMPARE_NODE_FIELD(fk_attrs);
 	COMPARE_NODE_FIELD(pk_attrs);
+	COMPARE_NODE_FIELD(fk_reftypes);
 	COMPARE_SCALAR_FIELD(fk_matchtype);
 	COMPARE_SCALAR_FIELD(fk_upd_action);
 	COMPARE_SCALAR_FIELD(fk_del_action);
diff --git a/src/backend/nodes/outfuncs.c b/src/backend/nodes/outfuncs.c
index 4a0e461d36..90b76d3dc9 100644
--- a/src/backend/nodes/outfuncs.c
+++ b/src/backend/nodes/outfuncs.c
@@ -3526,6 +3526,7 @@ _outConstraint(StringInfo str, const Constraint *node)
 			WRITE_NODE_FIELD(pktable);
 			WRITE_NODE_FIELD(fk_attrs);
 			WRITE_NODE_FIELD(pk_attrs);
+			WRITE_NODE_FIELD(fk_reftypes);
 			WRITE_CHAR_FIELD(fk_matchtype);
 			WRITE_CHAR_FIELD(fk_upd_action);
 			WRITE_CHAR_FIELD(fk_del_action);
diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y
index 9de9dbd8a8..58b11bcf3a 100644
--- a/src/backend/parser/gram.y
+++ b/src/backend/parser/gram.y
@@ -127,6 +127,13 @@ typedef struct ImportQual
 	List	   *table_names;
 } ImportQual;
 
+/* Private struct for the result of foreign_key_column_elem production */
+typedef struct FKColElem
+{
+	Node	   *name;			/* name of the column (a String) */
+	char		reftype;		/* FKCONSTR_REF_xxx code */
+} FKColElem;
+
 /* ConstraintAttributeSpec yields an integer bitmask of these flags: */
 #define CAS_NOT_DEFERRABLE			0x01
 #define CAS_DEFERRABLE				0x02
@@ -184,6 +191,7 @@ static RangeVar *makeRangeVarFromAnyName(List *names, int position, core_yyscan_
 static void SplitColQualList(List *qualList,
 							 List **constraintList, CollateClause **collClause,
 							 core_yyscan_t yyscanner);
+static void SplitFKColElems(List *fkcolelems, List **names, List **reftypes);
 static void processCASbits(int cas_bits, int location, const char *constrType,
 			   bool *deferrable, bool *initdeferred, bool *not_valid,
 			   bool *no_inherit, core_yyscan_t yyscanner);
@@ -234,6 +242,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
 	A_Indices			*aind;
 	ResTarget			*target;
 	struct PrivTarget	*privtarget;
+	struct FKColElem	*fkcolelem;
 	AccessPriv			*accesspriv;
 	struct ImportQual	*importqual;
 	InsertStmt			*istmt;
@@ -365,6 +374,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
 %type <accesspriv> privilege
 %type <list>	privileges privilege_list
 %type <privtarget> privilege_target
+%type <fkcolelem> foreign_key_column_elem
 %type <objwithargs> function_with_argtypes aggregate_with_argtypes operator_with_argtypes
 %type <list>	function_with_argtypes_list aggregate_with_argtypes_list operator_with_argtypes_list
 %type <ival>	defacl_privilege_target
@@ -401,7 +411,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
 				execute_param_clause using_clause returning_clause
 				opt_enum_val_list enum_val_list table_func_column_list
 				create_generic_options alter_generic_options
-				relation_expr_list dostmt_opt_list
+				relation_expr_list dostmt_opt_list foreign_key_column_list
 				transform_element_list transform_type_list
 				TriggerTransitions TriggerReferencing
 				publication_name_list
@@ -633,8 +643,8 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
 	DETACH DICTIONARY DISABLE_P DISCARD DISTINCT DO DOCUMENT_P DOMAIN_P
 	DOUBLE_P DROP
 
-	EACH ELSE ENABLE_P ENCODING ENCRYPTED END_P ENUM_P ESCAPE EVENT EXCEPT
-	EXCLUDE EXCLUDING EXCLUSIVE EXECUTE EXISTS EXPLAIN
+	EACH ELEMENT ELSE ENABLE_P ENCODING ENCRYPTED END_P ENUM_P ESCAPE
+	EVENT EXCEPT EXCLUDE EXCLUDING EXCLUSIVE EXECUTE EXISTS EXPLAIN
 	EXTENSION EXTERNAL EXTRACT
 
 	FALSE_P FAMILY FETCH FILTER FIRST_P FLOAT_P FOLLOWING FOR
@@ -3526,8 +3536,10 @@ ColConstraintElem:
 					n->contype = CONSTR_FOREIGN;
 					n->location = @1;
 					n->pktable			= $2;
+					/* fk_attrs will be filled in by parse analysis */
 					n->fk_attrs			= NIL;
 					n->pk_attrs			= $3;
+					n->fk_reftypes		= list_make1_int(FKCONSTR_REF_PLAIN);
 					n->fk_matchtype		= $4;
 					n->fk_upd_action	= (char) ($5 >> 8);
 					n->fk_del_action	= (char) ($5 & 0xFF);
@@ -3729,14 +3741,15 @@ ConstraintElem:
 								   NULL, yyscanner);
 					$$ = (Node *)n;
 				}
-			| FOREIGN KEY '(' columnList ')' REFERENCES qualified_name
-				opt_column_list key_match key_actions ConstraintAttributeSpec
+			| FOREIGN KEY '(' foreign_key_column_list ')' REFERENCES
+				qualified_name opt_column_list key_match key_actions
+				ConstraintAttributeSpec
 				{
 					Constraint *n = makeNode(Constraint);
 					n->contype = CONSTR_FOREIGN;
 					n->location = @1;
+					SplitFKColElems($4, &n->fk_attrs, &n->fk_reftypes);
 					n->pktable			= $7;
-					n->fk_attrs			= $4;
 					n->pk_attrs			= $8;
 					n->fk_matchtype		= $9;
 					n->fk_upd_action	= (char) ($10 >> 8);
@@ -3770,6 +3783,30 @@ columnElem: ColId
 				}
 		;
 
+foreign_key_column_list:
+			foreign_key_column_elem
+				{ $$ = list_make1($1); }
+			| foreign_key_column_list ',' foreign_key_column_elem
+				{ $$ = lappend($1, $3); }
+		;
+
+foreign_key_column_elem:
+			ColId
+				{
+					FKColElem *n = (FKColElem *) palloc(sizeof(FKColElem));
+					n->name = (Node *) makeString($1);
+					n->reftype = FKCONSTR_REF_PLAIN;
+					$$ = n;
+				}
+			| EACH ELEMENT OF ColId
+				{
+					FKColElem *n = (FKColElem *) palloc(sizeof(FKColElem));
+					n->name = (Node *) makeString($4);
+					n->reftype = FKCONSTR_REF_EACH_ELEMENT;
+					$$ = n;
+				}
+		;
+
 opt_c_include:	INCLUDE '(' columnList ')'			{ $$ = $3; }
 			 |		/* EMPTY */						{ $$ = NIL; }
 		;
@@ -15091,6 +15128,7 @@ unreserved_keyword:
 			| DOUBLE_P
 			| DROP
 			| EACH
+			| ELEMENT
 			| ENABLE_P
 			| ENCODING
 			| ENCRYPTED
@@ -16217,6 +16255,23 @@ SplitColQualList(List *qualList,
 	*constraintList = qualList;
 }
 
+/* Split a list of FKColElem structs into separate name and reftype lists */
+static void
+SplitFKColElems(List *fkcolelems, List **names, List **reftypes)
+{
+	ListCell   *lc;
+
+	*names = NIL;
+	*reftypes = NIL;
+	foreach(lc, fkcolelems)
+	{
+		FKColElem *fkcolelem = (FKColElem *) lfirst(lc);
+
+		*names = lappend(*names, fkcolelem->name);
+		*reftypes = lappend_int(*reftypes, fkcolelem->reftype);
+	}
+}
+
 /*
  * Process result of ConstraintAttributeSpec, and set appropriate bool flags
  * in the output command node.  Pass NULL for any flags the particular
diff --git a/src/backend/parser/parse_coerce.c b/src/backend/parser/parse_coerce.c
index 903478d8ca..f9edd583a8 100644
--- a/src/backend/parser/parse_coerce.c
+++ b/src/backend/parser/parse_coerce.c
@@ -1389,6 +1389,102 @@ select_common_type(ParseState *pstate, List *exprs, const char *context,
 	return ptype;
 }
 
+/*
+ * look at select_common_type(); in parse_coerce.c(src/backend/parser/parse_coerce.c)
+ *
+ * select_common_type_2args()
+ *		Determine the common supertype of a list of input expressions.
+ * 'leftOid': left operand's type
+ * 'rightOid': left operand's type
+ */
+Oid
+select_common_type_2args(Oid leftOid, Oid rightOid)
+{
+	TYPCATEGORY leftcategory;
+	TYPCATEGORY rightcategory;
+	bool		leftispreferred;
+	bool		rightispreferred;
+
+	Assert(leftOid != InvalidOid);
+	Assert(rightOid != InvalidOid);
+
+	/*
+	 * If input types are valid and exactly the same, just pick that type.
+	 */
+	if (leftOid != UNKNOWNOID)
+	{
+		if (rightOid == leftOid)
+			return leftOid;
+	}
+
+	/*
+	 * Nope, so set up for the full algorithm.
+	 */
+	leftOid = getBaseType(leftOid);
+	rightOid = getBaseType(rightOid);
+	get_type_category_preferred(leftOid, &leftcategory, &leftispreferred);
+	get_type_category_preferred(rightOid, &rightcategory, &rightispreferred);
+
+	if (rightOid != UNKNOWNOID && rightOid != leftOid)
+	{
+		if (rightcategory != leftcategory)
+		{
+			/* both types in different categories? then not much hope... */
+			return InvalidOid;
+		}
+
+		if (can_coerce_type(1, &rightOid, &leftOid, COERCION_IMPLICIT))
+		{
+			/* can coerce to it implicitly right to left */
+			if (!can_coerce_type(1, &leftOid, &rightOid, COERCION_IMPLICIT))
+			{
+				/*
+				 * can not coerce to it implicitly right to left, thus
+				 * coercion only works one way
+				 */
+				return leftOid;
+			}
+			else
+			{
+				/*
+				 * coercion works both ways, then decide depending on
+				 * preferred flag
+				 */
+				if (leftispreferred)
+					return leftOid;
+				else
+					return rightOid;
+			}
+		}
+		else
+		{
+			/* can not coerce to it implicitly right to left */
+			if (can_coerce_type(1, &leftOid, &rightOid, COERCION_IMPLICIT))
+			{
+				/*
+				 * can coerce to it implicitly right to left, thus coercion
+				 * only works one way
+				 */
+				return rightOid;
+			}
+			else
+			{
+				/* can not coerce either way */
+				return InvalidOid;
+			}
+		}
+	}
+
+	/*
+	 * If all the inputs were UNKNOWN type --- ie, unknown-type literals ---
+	 * then resolve as type TEXT.
+	 */
+	if (leftOid == UNKNOWNOID)
+		leftOid = TEXTOID;
+
+	return leftOid;
+}
+
 /*
  * coerce_to_common_type()
  *		Coerce an expression to the given type.
diff --git a/src/backend/parser/parse_utilcmd.c b/src/backend/parser/parse_utilcmd.c
index 577fe1e752..2ba14347d1 100644
--- a/src/backend/parser/parse_utilcmd.c
+++ b/src/backend/parser/parse_utilcmd.c
@@ -776,6 +776,8 @@ transformColumnDefinition(CreateStmtContext *cxt, ColumnDef *column)
 				 * list of FK constraints to be processed later.
 				 */
 				constraint->fk_attrs = list_make1(makeString(column->colname));
+				/* grammar should have set fk_reftypes */
+				Assert(list_length(constraint->fk_reftypes) == 1);
 				cxt->fkconstraints = lappend(cxt->fkconstraints, constraint);
 				break;
 
diff --git a/src/backend/utils/adt/ri_triggers.c b/src/backend/utils/adt/ri_triggers.c
index 76cd0edb45..8dad7c4b53 100644
--- a/src/backend/utils/adt/ri_triggers.c
+++ b/src/backend/utils/adt/ri_triggers.c
@@ -109,9 +109,11 @@ typedef struct RI_ConstraintInfo
 	char		confupdtype;	/* foreign key's ON UPDATE action */
 	char		confdeltype;	/* foreign key's ON DELETE action */
 	char		confmatchtype;	/* foreign key's match type */
+	bool		has_array;		/* true if any reftype is EACH_ELEMENT */
 	int			nkeys;			/* number of key columns */
 	int16		pk_attnums[RI_MAX_NUMKEYS]; /* attnums of referenced cols */
 	int16		fk_attnums[RI_MAX_NUMKEYS]; /* attnums of referencing cols */
+	char		fk_reftypes[RI_MAX_NUMKEYS];	/* reference semantics */
 	Oid			pf_eq_oprs[RI_MAX_NUMKEYS]; /* equality operators (PK = FK) */
 	Oid			pp_eq_oprs[RI_MAX_NUMKEYS]; /* equality operators (PK = PK) */
 	Oid			ff_eq_oprs[RI_MAX_NUMKEYS]; /* equality operators (FK = FK) */
@@ -185,7 +187,8 @@ static void ri_GenerateQual(StringInfo buf,
 							const char *sep,
 							const char *leftop, Oid leftoptype,
 							Oid opoid,
-							const char *rightop, Oid rightoptype);
+							const char *rightop, Oid rightoptype,
+							char fkreftype);
 static void ri_GenerateQualCollation(StringInfo buf, Oid collation);
 static int	ri_NullCheck(TupleDesc tupdesc, TupleTableSlot *slot,
 						 const RI_ConstraintInfo *riinfo, bool rel_is_pk);
@@ -344,6 +347,7 @@ RI_FKey_check(TriggerData *trigdata)
 	if ((qplan = ri_FetchPreparedPlan(&qkey)) == NULL)
 	{
 		StringInfoData querybuf;
+		StringInfoData countbuf;
 		char		pkrelname[MAX_QUOTED_REL_NAME_LEN];
 		char		attname[MAX_QUOTED_NAME_LEN];
 		char		paramname[16];
@@ -357,6 +361,14 @@ RI_FKey_check(TriggerData *trigdata)
 		 *		   FOR KEY SHARE OF x
 		 * The type id's for the $ parameters are those of the
 		 * corresponding FK attributes.
+		 *
+		 * In case of an array ELEMENT foreign key, the previous query is used
+		 * to count the number of matching rows and see if every combination
+		 * is actually referenced.
+		 * The wrapping query is
+		 *	SELECT 1 WHERE
+		 *	  (SELECT count(DISTINCT y) FROM unnest($1) y)
+		 *	  = (SELECT count(*) FROM (<QUERY>) z)
 		 * ----------
 		 */
 		initStringInfo(&querybuf);
@@ -366,6 +378,13 @@ RI_FKey_check(TriggerData *trigdata)
 		appendStringInfo(&querybuf, "SELECT 1 FROM %s%s x",
 						 pk_only, pkrelname);
 		querysep = "WHERE";
+
+		if (riinfo->has_array)
+		{
+			initStringInfo(&countbuf);
+			appendStringInfo(&countbuf, "SELECT 1 WHERE ");
+		}
+
 		for (int i = 0; i < riinfo->nkeys; i++)
 		{
 			Oid			pk_type = RIAttType(pk_rel, riinfo->pk_attnums[i]);
@@ -374,18 +393,41 @@ RI_FKey_check(TriggerData *trigdata)
 			quoteOneName(attname,
 						 RIAttName(pk_rel, riinfo->pk_attnums[i]));
 			sprintf(paramname, "$%d", i + 1);
+
+			/*
+			 * In case of an array ELEMENT foreign key, we check that each
+			 * distinct non-null value in the array is present in the PK
+			 * table.
+			 */
+			if (riinfo->fk_reftypes[i] == FKCONSTR_REF_EACH_ELEMENT)
+				appendStringInfo(&countbuf,
+								 "(SELECT pg_catalog.count(DISTINCT y) FROM pg_catalog.unnest(%s) y)",
+								 paramname);
+
 			ri_GenerateQual(&querybuf, querysep,
 							attname, pk_type,
 							riinfo->pf_eq_oprs[i],
-							paramname, fk_type);
+							paramname, fk_type,
+							riinfo->fk_reftypes[i]);
 			querysep = "AND";
 			queryoids[i] = fk_type;
 		}
 		appendStringInfoString(&querybuf, " FOR KEY SHARE OF x");
 
-		/* Prepare and save the plan */
-		qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
-							 &qkey, fk_rel, pk_rel, true);
+		if (riinfo->has_array)
+		{
+			appendStringInfo(&countbuf,
+							 " OPERATOR(pg_catalog.=) (SELECT pg_catalog.count(*) FROM (%s) z)",
+							 querybuf.data);
+
+			/* Prepare and save the plan for Array Element Foreign Keys */
+			qplan = ri_PlanCheck(countbuf.data, riinfo->nkeys, queryoids,
+								 &qkey, fk_rel, pk_rel, true);
+		}
+		else
+			/* Prepare and save the plan */
+			qplan = ri_PlanCheck(querybuf.data, riinfo->nkeys, queryoids,
+								 &qkey, fk_rel, pk_rel, true);
 	}
 
 	/*
@@ -504,7 +546,8 @@ ri_Check_Pk_Match(Relation pk_rel, Relation fk_rel,
 			ri_GenerateQual(&querybuf, querysep,
 							attname, pk_type,
 							riinfo->pp_eq_oprs[i],
-							paramname, pk_type);
+							paramname, pk_type,
+							FKCONSTR_REF_PLAIN);
 			querysep = "AND";
 			queryoids[i] = pk_type;
 		}
@@ -694,7 +737,8 @@ ri_restrict(TriggerData *trigdata, bool is_no_action)
 			ri_GenerateQual(&querybuf, querysep,
 							paramname, pk_type,
 							riinfo->pf_eq_oprs[i],
-							attname, fk_type);
+							attname, fk_type,
+							riinfo->fk_reftypes[i]);
 			if (pk_coll != fk_coll && !get_collation_isdeterministic(pk_coll))
 				ri_GenerateQualCollation(&querybuf, pk_coll);
 			querysep = "AND";
@@ -800,7 +844,8 @@ RI_FKey_cascade_del(PG_FUNCTION_ARGS)
 			ri_GenerateQual(&querybuf, querysep,
 							paramname, pk_type,
 							riinfo->pf_eq_oprs[i],
-							attname, fk_type);
+							attname, fk_type,
+							riinfo->fk_reftypes[i]);
 			if (pk_coll != fk_coll && !get_collation_isdeterministic(pk_coll))
 				ri_GenerateQualCollation(&querybuf, pk_coll);
 			querysep = "AND";
@@ -919,7 +964,8 @@ RI_FKey_cascade_upd(PG_FUNCTION_ARGS)
 			ri_GenerateQual(&qualbuf, qualsep,
 							paramname, pk_type,
 							riinfo->pf_eq_oprs[i],
-							attname, fk_type);
+							attname, fk_type,
+							riinfo->fk_reftypes[i]);
 			if (pk_coll != fk_coll && !get_collation_isdeterministic(pk_coll))
 				ri_GenerateQualCollation(&querybuf, pk_coll);
 			querysep = ",";
@@ -1099,7 +1145,8 @@ ri_set(TriggerData *trigdata, bool is_set_null)
 			ri_GenerateQual(&qualbuf, qualsep,
 							paramname, pk_type,
 							riinfo->pf_eq_oprs[i],
-							attname, fk_type);
+							attname, fk_type,
+							riinfo->fk_reftypes[i]);
 			if (pk_coll != fk_coll && !get_collation_isdeterministic(pk_coll))
 				ri_GenerateQualCollation(&querybuf, pk_coll);
 			querysep = ",";
@@ -1372,6 +1419,14 @@ RI_Initial_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
 	 * For MATCH FULL:
 	 *	 (fk.keycol1 IS NOT NULL [OR ...])
 	 *
+	 * In case of an array ELEMENT column, relname is replaced with the
+	 * following subquery:
+	 *
+	 *	 SELECT unnest("keycol1") k1, "keycol1" ak1 [, ...]
+	 *	 FROM ONLY "public"."fk"
+	 *
+	 * where all the columns are renamed in order to prevent name collisions.
+	 *
 	 * We attach COLLATE clauses to the operators when comparing columns
 	 * that have different collations.
 	 *----------
@@ -1389,13 +1444,35 @@ RI_Initial_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
 
 	quoteRelationName(pkrelname, pk_rel);
 	quoteRelationName(fkrelname, fk_rel);
-	fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
-		"" : "ONLY ";
-	pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
-		"" : "ONLY ";
-	appendStringInfo(&querybuf,
-					 " FROM %s%s fk LEFT OUTER JOIN %s%s pk ON",
-					 fk_only, fkrelname, pk_only, pkrelname);
+
+	if (riinfo->has_array)
+	{
+		appendStringInfo(&querybuf, " FROM ONLY %s fk", fkrelname);
+		for (int i = 0; i < riinfo->nkeys; i++)
+		{
+			if (riinfo->fk_reftypes[i] != FKCONSTR_REF_EACH_ELEMENT)
+				continue;
+
+			quoteOneName(fkattname,
+						 RIAttName(fk_rel, riinfo->fk_attnums[i]));
+			appendStringInfo(&querybuf,
+							 " CROSS JOIN LATERAL pg_catalog.unnest(fk.%s) a (e)",
+							 fkattname);
+		}
+		appendStringInfo(&querybuf,
+						 " LEFT OUTER JOIN ONLY %s pk ON",
+						 pkrelname);
+	}
+	else
+	{
+		fk_only = fk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
+			"" : "ONLY ";
+		pk_only = pk_rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE ?
+			"" : "ONLY ";
+		appendStringInfo(&querybuf,
+						" FROM %s%s fk LEFT OUTER JOIN %s%s pk ON",
+						fk_only, fkrelname, pk_only, pkrelname);
+	}
 
 	strcpy(pkattname, "pk.");
 	strcpy(fkattname, "fk.");
@@ -1406,15 +1483,23 @@ RI_Initial_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
 		Oid			fk_type = RIAttType(fk_rel, riinfo->fk_attnums[i]);
 		Oid			pk_coll = RIAttCollation(pk_rel, riinfo->pk_attnums[i]);
 		Oid			fk_coll = RIAttCollation(fk_rel, riinfo->fk_attnums[i]);
+		char	   *tmp;
 
 		quoteOneName(pkattname + 3,
 					 RIAttName(pk_rel, riinfo->pk_attnums[i]));
-		quoteOneName(fkattname + 3,
-					 RIAttName(fk_rel, riinfo->fk_attnums[i]));
+		if (riinfo->fk_reftypes[i] == FKCONSTR_REF_EACH_ELEMENT)
+			tmp = "a.e";
+		else
+		{
+			quoteOneName(fkattname + 3,
+						 RIAttName(fk_rel, riinfo->fk_attnums[i]));
+			tmp = fkattname;
+		}
 		ri_GenerateQual(&querybuf, sep,
 						pkattname, pk_type,
 						riinfo->pf_eq_oprs[i],
-						fkattname, fk_type);
+						tmp, fk_type,
+						FKCONSTR_REF_PLAIN);
 		if (pk_coll != fk_coll)
 			ri_GenerateQualCollation(&querybuf, pk_coll);
 		sep = "AND";
@@ -1430,10 +1515,15 @@ RI_Initial_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
 	sep = "";
 	for (int i = 0; i < riinfo->nkeys; i++)
 	{
-		quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
-		appendStringInfo(&querybuf,
-						 "%sfk.%s IS NOT NULL",
-						 sep, fkattname);
+		if (riinfo->fk_reftypes[i] == FKCONSTR_REF_EACH_ELEMENT)
+			appendStringInfo(&querybuf, "%sa.e IS NOT NULL", sep);
+		else
+		{
+			quoteOneName(fkattname, RIAttName(fk_rel, riinfo->fk_attnums[i]));
+			appendStringInfo(&querybuf,
+							 "%sfk.%s IS NOT NULL",
+							 sep, fkattname);
+		}
 		switch (riinfo->confmatchtype)
 		{
 			case FKCONSTR_MATCH_SIMPLE:
@@ -1644,7 +1734,8 @@ RI_PartitionRemove_Check(Trigger *trigger, Relation fk_rel, Relation pk_rel)
 		ri_GenerateQual(&querybuf, sep,
 						pkattname, pk_type,
 						riinfo->pf_eq_oprs[i],
-						fkattname, fk_type);
+						fkattname, fk_type,
+						riinfo->fk_reftypes[i]);
 		if (pk_coll != fk_coll)
 			ri_GenerateQualCollation(&querybuf, pk_coll);
 		sep = "AND";
@@ -1814,21 +1905,23 @@ quoteRelationName(char *buffer, Relation rel)
 /*
  * ri_GenerateQual --- generate a WHERE clause equating two variables
  *
- * This basically appends " sep leftop op rightop" to buf, adding casts
- * and schema qualification as needed to ensure that the parser will select
- * the operator we specify.  leftop and rightop should be parenthesized
- * if they aren't variables or parameters.
+ * This basically appends " sep leftop op rightop" to buf, or if fkreftype is
+ * FKCONSTR_REF_EACH_ELEMENT, append " sep rightop @> leftop", adding casts and
+ * schema qualification as needed to ensure that the parser will select the
+ * operator we specify.  leftop and rightop should be parenthesized if they
+ * aren't variables or parameters.
  */
 static void
 ri_GenerateQual(StringInfo buf,
 				const char *sep,
 				const char *leftop, Oid leftoptype,
 				Oid opoid,
-				const char *rightop, Oid rightoptype)
+				const char *rightop, Oid rightoptype,
+				char fkreftype)
 {
 	appendStringInfo(buf, " %s ", sep);
 	generate_operator_clause(buf, leftop, leftoptype, opoid,
-							 rightop, rightoptype);
+							 rightop, rightoptype, fkreftype);
 }
 
 /*
@@ -2011,6 +2104,7 @@ ri_LoadConstraintInfo(Oid constraintOid)
 	bool		found;
 	HeapTuple	tup;
 	Form_pg_constraint conForm;
+	int 		i;
 
 	/*
 	 * On the first call initialize the hashtable
@@ -2058,7 +2152,26 @@ ri_LoadConstraintInfo(Oid constraintOid)
 							   riinfo->pk_attnums,
 							   riinfo->pf_eq_oprs,
 							   riinfo->pp_eq_oprs,
-							   riinfo->ff_eq_oprs);
+							   riinfo->ff_eq_oprs,
+							   riinfo->fk_reftypes);
+
+	/*
+	 * Fix up some stuff for Array Element Foreign Keys.  We need a has_array
+	 * flag indicating whether there's an array foreign key, and we want to
+	 * set ff_eq_oprs[i] to array_eq() for array columns, because that's what
+	 * makes sense for ri_KeysEqual, and we have no other use for ff_eq_oprs
+	 * in this module.  (If we did, substituting the array comparator at the
+	 * call point in ri_KeysEqual might be more appropriate.)
+	 */
+	riinfo->has_array = false;
+	for (i = 0; i < riinfo->nkeys; i++)
+	{
+		if (riinfo->fk_reftypes[i] != FKCONSTR_REF_PLAIN)
+		{
+			riinfo->has_array = true;
+			riinfo->ff_eq_oprs[i] = ARRAY_EQ_OP;
+		}
+	}
 
 	ReleaseSysCache(tup);
 
@@ -2445,6 +2558,10 @@ ri_ReportViolation(const RI_ConstraintInfo *riinfo,
 				appendStringInfoString(&key_names, ", ");
 				appendStringInfoString(&key_values, ", ");
 			}
+
+			if (riinfo->fk_reftypes[idx] == FKCONSTR_REF_EACH_ELEMENT)
+				appendStringInfoString(&key_names, "EACH ELEMENT OF ");
+
 			appendStringInfoString(&key_names, name);
 			appendStringInfoString(&key_values, val);
 		}
diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c
index 1268ac1dd0..be8ec1c79f 100644
--- a/src/backend/utils/adt/ruleutils.c
+++ b/src/backend/utils/adt/ruleutils.c
@@ -56,6 +56,7 @@
 #include "parser/parse_oper.h"
 #include "parser/parser.h"
 #include "parser/parsetree.h"
+#include "parser/parse_coerce.h"
 #include "rewrite/rewriteHandler.h"
 #include "rewrite/rewriteManip.h"
 #include "rewrite/rewriteSupport.h"
@@ -318,6 +319,9 @@ static char *pg_get_viewdef_worker(Oid viewoid,
 static char *pg_get_triggerdef_worker(Oid trigid, bool pretty);
 static int	decompile_column_index_array(Datum column_index_array, Oid relId,
 										 StringInfo buf);
+static void decompile_fk_column_index_array(Datum column_index_array,
+											Datum fk_reftype_array,
+											Oid relId, StringInfo buf);
 static char *pg_get_ruledef_worker(Oid ruleoid, int prettyFlags);
 static char *pg_get_indexdef_worker(Oid indexrelid, int colno,
 									const Oid *excludeOps,
@@ -1983,7 +1987,8 @@ pg_get_constraintdef_worker(Oid constraintId, bool fullCommand,
 	{
 		case CONSTRAINT_FOREIGN:
 			{
-				Datum		val;
+				Datum		colindexes;
+				Datum		reftypes;
 				bool		isnull;
 				const char *string;
 
@@ -1991,13 +1996,21 @@ pg_get_constraintdef_worker(Oid constraintId, bool fullCommand,
 				appendStringInfoString(&buf, "FOREIGN KEY (");
 
 				/* Fetch and build referencing-column list */
-				val = SysCacheGetAttr(CONSTROID, tup,
-									  Anum_pg_constraint_conkey, &isnull);
+				colindexes = SysCacheGetAttr(CONSTROID, tup,
+											 Anum_pg_constraint_conkey,
+											 &isnull);
 				if (isnull)
 					elog(ERROR, "null conkey for constraint %u",
 						 constraintId);
+				reftypes = SysCacheGetAttr(CONSTROID, tup,
+										   Anum_pg_constraint_confreftype,
+										   &isnull);
+				if (isnull)
+					elog(ERROR, "null confreftype for constraint %u",
+						 constraintId);
 
-				decompile_column_index_array(val, conForm->conrelid, &buf);
+				decompile_fk_column_index_array(colindexes, reftypes,
+												conForm->conrelid, &buf);
 
 				/* add foreign relation name */
 				appendStringInfo(&buf, ") REFERENCES %s(",
@@ -2005,13 +2018,15 @@ pg_get_constraintdef_worker(Oid constraintId, bool fullCommand,
 														NIL));
 
 				/* Fetch and build referenced-column list */
-				val = SysCacheGetAttr(CONSTROID, tup,
-									  Anum_pg_constraint_confkey, &isnull);
+				colindexes = SysCacheGetAttr(CONSTROID, tup,
+											 Anum_pg_constraint_confkey,
+											 &isnull);
 				if (isnull)
 					elog(ERROR, "null confkey for constraint %u",
 						 constraintId);
 
-				decompile_column_index_array(val, conForm->confrelid, &buf);
+				decompile_column_index_array(colindexes,
+											 conForm->confrelid, &buf);
 
 				appendStringInfoChar(&buf, ')');
 
@@ -2340,6 +2355,66 @@ decompile_column_index_array(Datum column_index_array, Oid relId,
 	return nKeys;
 }
 
+/*
+ * Convert an int16[] Datum and a char[] Datum into a comma-separated list of
+ * column names for the indicated relation, prefixed by appropriate keywords
+ * depending on the foreign key reference semantics indicated by the char[]
+ * entries.  Append the text to buf.
+ */
+static void
+decompile_fk_column_index_array(Datum column_index_array,
+								Datum fk_reftype_array,
+								Oid relId, StringInfo buf)
+{
+	Datum	   *keys;
+	int			nKeys;
+	Datum	   *reftypes;
+	int			nReftypes;
+	int			j;
+
+	/* Extract data from array of int16 */
+	deconstruct_array(DatumGetArrayTypeP(column_index_array),
+					  INT2OID, sizeof(int16), true, 's',
+					  &keys, NULL, &nKeys);
+
+	/* Extract data from array of char */
+	deconstruct_array(DatumGetArrayTypeP(fk_reftype_array),
+					  CHAROID, sizeof(char), true, 'c',
+					  &reftypes, NULL, &nReftypes);
+
+	if (nKeys != nReftypes)
+		elog(ERROR, "wrong confreftype cardinality");
+
+	for (j = 0; j < nKeys; j++)
+	{
+		char	   *colName;
+		const char *prefix;
+
+		colName = get_attname(relId, DatumGetInt16(keys[j]), false);
+
+		switch (DatumGetChar(reftypes[j]))
+		{
+			case FKCONSTR_REF_PLAIN:
+				prefix = "";
+				break;
+			case FKCONSTR_REF_EACH_ELEMENT:
+				prefix = "EACH ELEMENT OF ";
+				break;
+			default:
+				elog(ERROR, "invalid fk_reftype: %d",
+					 (int) DatumGetChar(reftypes[j]));
+				prefix = NULL;	/* keep compiler quiet */
+				break;
+		}
+
+		if (j == 0)
+			appendStringInfo(buf, "%s%s", prefix,
+							 quote_identifier(colName));
+		else
+			appendStringInfo(buf, ", %s%s", prefix,
+							 quote_identifier(colName));
+	}
+}
 
 /* ----------
  * get_expr			- Decompile an expression tree
@@ -11056,7 +11131,8 @@ void
 generate_operator_clause(StringInfo buf,
 						 const char *leftop, Oid leftoptype,
 						 Oid opoid,
-						 const char *rightop, Oid rightoptype)
+						 const char *rightop, Oid rightoptype,
+						 char fkreftype)
 {
 	HeapTuple	opertup;
 	Form_pg_operator operform;
@@ -11072,14 +11148,62 @@ generate_operator_clause(StringInfo buf,
 
 	nspname = get_namespace_name(operform->oprnamespace);
 
-	appendStringInfoString(buf, leftop);
-	if (leftoptype != operform->oprleft)
-		add_cast_to(buf, operform->oprleft);
-	appendStringInfo(buf, " OPERATOR(%s.", quote_identifier(nspname));
-	appendStringInfoString(buf, oprname);
-	appendStringInfo(buf, ") %s", rightop);
-	if (rightoptype != operform->oprright)
-		add_cast_to(buf, operform->oprright);
+	if (fkreftype == FKCONSTR_REF_EACH_ELEMENT)
+	{
+		Oid			oprright;
+		Oid			oprleft;
+		Oid			oprcommon;
+
+		/*
+		 * we first need to get the array types and decide the more
+		 * appropriate one
+		 */
+
+		/* get array type of refrenced element */
+		oprright = get_array_type(operform->oprleft);
+		if (!OidIsValid(oprright))
+			ereport(ERROR,
+					(errcode(ERRCODE_UNDEFINED_OBJECT),
+					 errmsg("could not find array type for data type %s",
+							format_type_be(operform->oprleft))));
+		/* get array type of refrencing element */
+		oprleft = get_array_type(operform->oprright);
+		if (!OidIsValid(oprleft))
+			ereport(ERROR,
+					(errcode(ERRCODE_UNDEFINED_OBJECT),
+					 errmsg("could not find array type for data type %s",
+							format_type_be(operform->oprright))));
+
+		/*
+		 * compare the two array types and try to find a common supertype
+		 */
+		oprcommon = select_common_type_2args(oprleft, oprright);
+		if (!OidIsValid(oprcommon))
+			ereport(ERROR,
+					(errcode(ERRCODE_UNDEFINED_OBJECT),
+					 errmsg("could not find common type between %s and %s",
+							format_type_be(oprleft), format_type_be(oprright))));
+
+		appendStringInfoString(buf, rightop);
+		if (oprleft != oprcommon)
+			add_cast_to(buf, oprcommon);
+		appendStringInfo(buf, " OPERATOR(pg_catalog.");
+		appendStringInfo(buf, " @>");
+		appendStringInfo(buf, ") ARRAY[%s]", leftop);
+		if (oprright != oprcommon)
+			add_cast_to(buf, oprcommon);
+	}
+	else
+	{
+		appendStringInfoString(buf, leftop);
+		if (leftoptype != operform->oprleft)
+			add_cast_to(buf, operform->oprleft);
+		appendStringInfo(buf, " OPERATOR(%s.", quote_identifier(nspname));
+		appendStringInfoString(buf, oprname);
+		appendStringInfo(buf, ") %s", rightop);
+		if (rightoptype != operform->oprright)
+			add_cast_to(buf, operform->oprright);
+	}
 
 	ReleaseSysCache(opertup);
 }
diff --git a/src/backend/utils/cache/relcache.c b/src/backend/utils/cache/relcache.c
index d0ad738c24..8b7524f162 100644
--- a/src/backend/utils/cache/relcache.c
+++ b/src/backend/utils/cache/relcache.c
@@ -4289,7 +4289,8 @@ RelationGetFKeyList(Relation relation)
 								   info->conkey,
 								   info->confkey,
 								   info->conpfeqop,
-								   NULL, NULL);
+								   NULL, NULL,
+								   NULL);
 
 		/* Add FK's node to the result list */
 		result = lappend(result, info);
diff --git a/src/include/catalog/pg_constraint.h b/src/include/catalog/pg_constraint.h
index c1e60c7dfd..c6c17f5b18 100644
--- a/src/include/catalog/pg_constraint.h
+++ b/src/include/catalog/pg_constraint.h
@@ -116,9 +116,17 @@ CATALOG(pg_constraint,2606,ConstraintRelationId)
 	 */
 	int16		confkey[1];
 
+	/*
+	 * If a foreign key, the reference semantics for each column
+	 */
+	char		confreftype[1];
+
 	/*
 	 * If a foreign key, the OIDs of the PK = FK equality operators for each
 	 * column of the constraint
+	 *
+	 * Note: for FArray Element Foreign Keys, all these operators are for the
+	 * array's element type.
 	 */
 	Oid			conpfeqop[1];
 
@@ -198,6 +206,7 @@ extern Oid	CreateConstraintEntry(const char *constraintName,
 								  Oid indexRelId,
 								  Oid foreignRelId,
 								  const int16 *foreignKey,
+								  const char *foreignRefType,
 								  const Oid *pfEqOp,
 								  const Oid *ppEqOp,
 								  const Oid *ffEqOp,
@@ -238,7 +247,8 @@ extern Bitmapset *get_primary_key_attnos(Oid relid, bool deferrableOk,
 										 Oid *constraintOid);
 extern void DeconstructFkConstraintRow(HeapTuple tuple, int *numfks,
 									   AttrNumber *conkey, AttrNumber *confkey,
-									   Oid *pf_eq_oprs, Oid *pp_eq_oprs, Oid *ff_eq_oprs);
+									   Oid *pf_eq_oprs, Oid *pp_eq_oprs, Oid *ff_eq_oprs,
+									   char *fk_reftypes);
 
 extern bool check_functional_grouping(Oid relid,
 									  Index varno, Index varlevelsup,
diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h
index 96ad25208c..7ff35c8180 100644
--- a/src/include/nodes/parsenodes.h
+++ b/src/include/nodes/parsenodes.h
@@ -2129,6 +2129,10 @@ typedef enum ConstrType			/* types of constraints */
 #define FKCONSTR_MATCH_PARTIAL		'p'
 #define FKCONSTR_MATCH_SIMPLE		's'
 
+ /* Foreign key column reference semantics codes */
+#define FKCONSTR_REF_PLAIN			'p'
+#define FKCONSTR_REF_EACH_ELEMENT	'e'
+
 typedef struct Constraint
 {
 	NodeTag		type;
@@ -2169,6 +2173,7 @@ typedef struct Constraint
 	RangeVar   *pktable;		/* Primary key table */
 	List	   *fk_attrs;		/* Attributes of foreign key */
 	List	   *pk_attrs;		/* Corresponding attrs in PK table */
+	List	   *fk_reftypes;	/* Per-column reference semantics (int List) */
 	char		fk_matchtype;	/* FULL, PARTIAL, SIMPLE */
 	char		fk_upd_action;	/* ON UPDATE action */
 	char		fk_del_action;	/* ON DELETE action */
diff --git a/src/include/parser/kwlist.h b/src/include/parser/kwlist.h
index 00ace8425e..ff4dcc969d 100644
--- a/src/include/parser/kwlist.h
+++ b/src/include/parser/kwlist.h
@@ -140,6 +140,7 @@ PG_KEYWORD("domain", DOMAIN_P, UNRESERVED_KEYWORD)
 PG_KEYWORD("double", DOUBLE_P, UNRESERVED_KEYWORD)
 PG_KEYWORD("drop", DROP, UNRESERVED_KEYWORD)
 PG_KEYWORD("each", EACH, UNRESERVED_KEYWORD)
+PG_KEYWORD("element", ELEMENT, UNRESERVED_KEYWORD)
 PG_KEYWORD("else", ELSE, RESERVED_KEYWORD)
 PG_KEYWORD("enable", ENABLE_P, UNRESERVED_KEYWORD)
 PG_KEYWORD("encoding", ENCODING, UNRESERVED_KEYWORD)
diff --git a/src/include/parser/parse_coerce.h b/src/include/parser/parse_coerce.h
index 37d73ae2cc..19cdbf7f46 100644
--- a/src/include/parser/parse_coerce.h
+++ b/src/include/parser/parse_coerce.h
@@ -67,6 +67,7 @@ extern int	parser_coercion_errposition(ParseState *pstate,
 
 extern Oid	select_common_type(ParseState *pstate, List *exprs,
 							   const char *context, Node **which_expr);
+extern Oid	select_common_type_2args(Oid ptype, Oid ntype);
 extern Node *coerce_to_common_type(ParseState *pstate, Node *node,
 								   Oid targetTypeId,
 								   const char *context);
diff --git a/src/include/utils/builtins.h b/src/include/utils/builtins.h
index a3cd7d26fa..7a15b5fb26 100644
--- a/src/include/utils/builtins.h
+++ b/src/include/utils/builtins.h
@@ -69,7 +69,8 @@ extern char *quote_qualified_identifier(const char *qualifier,
 extern void generate_operator_clause(fmStringInfo buf,
 									 const char *leftop, Oid leftoptype,
 									 Oid opoid,
-									 const char *rightop, Oid rightoptype);
+									 const char *rightop, Oid rightoptype,
+									 char fkreftype);
 
 /* varchar.c */
 extern int	bpchartruelen(char *s, int len);
diff --git a/src/test/regress/parallel_schedule b/src/test/regress/parallel_schedule
index 3710bc8ee0..9eb7fbd2e0 100644
--- a/src/test/regress/parallel_schedule
+++ b/src/test/regress/parallel_schedule
@@ -78,7 +78,7 @@ test: brin gin gist spgist privileges init_privs security_label collate matview
 # ----------
 # Another group of parallel tests
 # ----------
-test: create_table_like alter_generic alter_operator misc async dbsize misc_functions sysviews tsrf tid tidscan
+test: create_table_like alter_generic alter_operator misc async dbsize misc_functions sysviews tsrf tid tidscan element_fk
 
 # rules cannot run concurrently with any test that creates
 # a view or rule in the public schema
diff --git a/src/test/regress/serial_schedule b/src/test/regress/serial_schedule
index eead306a34..fd032f9d16 100644
--- a/src/test/regress/serial_schedule
+++ b/src/test/regress/serial_schedule
@@ -135,6 +135,7 @@ test: sysviews
 test: tsrf
 test: tid
 test: tidscan
+test: element_fk
 test: rules
 test: psql
 test: psql_crosstab
