#include "postgres.h"
 
 #include "executor/executor.h"
+#include "miscadmin.h"
 #include "parser/parse_oper.h"
 #include "utils/lsyscache.h"
 #include "utils/memutils.h"
 BuildTupleHashTable(int numCols, AttrNumber *keyColIdx,
                    FmgrInfo *eqfunctions,
                    FmgrInfo *hashfunctions,
-                   int nbuckets, Size entrysize,
+                   long nbuckets, Size entrysize,
                    MemoryContext tablecxt, MemoryContext tempcxt)
 {
    TupleHashTable hashtable;
    Assert(nbuckets > 0);
    Assert(entrysize >= sizeof(TupleHashEntryData));
 
+   /* Limit initial table size request to not more than work_mem */
+   nbuckets = Min(nbuckets, (long) ((work_mem * 1024L) / entrysize));
+
    hashtable = (TupleHashTable) MemoryContextAlloc(tablecxt,
                                                 sizeof(TupleHashTableData));
 
    hash_ctl.hash = TupleHashTableHash;
    hash_ctl.match = TupleHashTableMatch;
    hash_ctl.hcxt = tablecxt;
-   hashtable->hashtab = hash_create("TupleHashTable", (long) nbuckets,
+   hashtable->hashtab = hash_create("TupleHashTable", nbuckets,
                                     &hash_ctl,
                    HASH_ELEM | HASH_FUNCTION | HASH_COMPARE | HASH_CONTEXT);
 
 
    int         ncols = list_length(subplan->paramIds);
    ExprContext *innerecontext = node->innerecontext;
    MemoryContext oldcontext;
-   int         nbuckets;
+   long        nbuckets;
    TupleTableSlot *slot;
 
    Assert(subplan->subLinkType == ANY_SUBLINK);
    node->havehashrows = false;
    node->havenullrows = false;
 
-   nbuckets = (int) ceil(planstate->plan->plan_rows);
+   nbuckets = (long) Min(planstate->plan->plan_rows, (double) LONG_MAX);
    if (nbuckets < 1)
        nbuckets = 1;
 
 
 extern TupleHashTable BuildTupleHashTable(int numCols, AttrNumber *keyColIdx,
                    FmgrInfo *eqfunctions,
                    FmgrInfo *hashfunctions,
-                   int nbuckets, Size entrysize,
+                   long nbuckets, Size entrysize,
                    MemoryContext tablecxt,
                    MemoryContext tempcxt);
 extern TupleHashEntry LookupTupleHashEntry(TupleHashTable hashtable,