 pgadmin/ctl/ctlSQLResult.cpp | 54 ++++++++++++++++++++++++++++++++------------
 1 file changed, 40 insertions(+), 14 deletions(-)

diff --git a/pgadmin/ctl/ctlSQLResult.cpp b/pgadmin/ctl/ctlSQLResult.cpp
index c0d2e10..74e4133 100644
--- a/pgadmin/ctl/ctlSQLResult.cpp
+++ b/pgadmin/ctl/ctlSQLResult.cpp
@@ -109,6 +109,7 @@ bool ctlSQLResult::IsColText(int col)
 
 int ctlSQLResult::Execute(const wxString &query, int resultToRetrieve, wxWindow *caller, long eventId, void *data)
 {
+	// Save current column's sizes
 	colSizes.Empty();
 	colHeaders.Empty();
 	for (int col = 0 ; col < GetNumberCols() ; col++)
@@ -214,28 +215,23 @@ void ctlSQLResult::DisplayData(bool single)
 	}
 	else
 	{
-		wxString colName, colType;
-		int w;
+		wxString colHeader;
+		int newSize, oldSize, maxSize, totalSize = 0, availSize;
 
 		size_t hdrIndex = 0;
 		long col, nCols = thread->DataSet()->NumCols();
 
+		// Ask WxGrid to make columns wide enough to fit most wide header or cell data
+		AutoSizeColumns(false);
+
 		for (col = 0 ; col < nCols ; col++)
 		{
-			colName = thread->DataSet()->ColName(col);
-			colType = thread->DataSet()->ColFullType(col);
-			colNames.Add(colName);
-			colTypes.Add(colType);
+			colNames.Add(thread->DataSet()->ColName(col));
+			colTypes.Add(thread->DataSet()->ColFullType(col));
 			colTypClasses.Add(thread->DataSet()->ColTypClass(col));
+			
+			totalSize += GetColSize(col);
 
-			wxString colHeader = colName + wxT("\n") + colType;
-
-			if (hdrIndex < colHeaders.GetCount() && colHeaders.Item(hdrIndex) == colHeader)
-				w = colSizes.Item(hdrIndex++);
-			else
-				w = -1;
-
-			SetColSize(col, w);
 			if (thread->DataSet()->ColTypClass(col) == PGTYPCLASS_NUMERIC)
 			{
 				/*
@@ -246,6 +242,36 @@ void ctlSQLResult::DisplayData(bool single)
 				SetColAttr(col, attr);
 			}
 		}
+		
+		availSize = GetClientSize().GetWidth() - GetRowLabelSize();
+		if (colSizes.GetCount() > 0 || totalSize > availSize)
+		{
+			// A wide column shouldn't take up more than 50% of the visible space
+			maxSize = availSize / 2;
+			for (col = 0 ; col < nCols ; col++)
+			{
+				oldSize = GetColSize(col);
+
+				colHeader = this->GetColLabelValue(col);
+				if (hdrIndex < colHeaders.GetCount() && colHeaders.Item(hdrIndex) == colHeader)
+				{	// Restore previously saved size
+					newSize = colSizes.Item(hdrIndex++);
+					SetColSize(col, newSize);
+					totalSize += newSize - oldSize;
+				}
+				else if(oldSize > maxSize)
+				{	
+					totalSize -= oldSize;
+					/* Shrink extra-wide column to maxSize.
+					 * If the rest of the columns are short, make sure to use all the remaining space,
+					 *   but no more than oldSize (which is enough according to AutoSizeColumns())
+					 */
+					newSize = wxMin(oldSize, wxMax(maxSize, availSize - totalSize));
+					SetColSize(col, newSize);
+					totalSize += newSize;
+				}
+			}
+		}
 	}
 	Thaw();
 }
