 pgadmin/ctl/ctlSQLResult.cpp | 35 +++++++++++++++++++++++++++--------
 1 file changed, 27 insertions(+), 8 deletions(-)

diff --git a/pgadmin/ctl/ctlSQLResult.cpp b/pgadmin/ctl/ctlSQLResult.cpp
index c0d2e10..4dfc49c 100644
--- a/pgadmin/ctl/ctlSQLResult.cpp
+++ b/pgadmin/ctl/ctlSQLResult.cpp
@@ -215,11 +215,17 @@ void ctlSQLResult::DisplayData(bool single)
 	else
 	{
 		wxString colName, colType;
-		int w;
+		int newWidth, oldWidth, maxWidth, sumWidth, availWidth;
 
 		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();
+
+		sumWidth = 0;
+		availWidth = GetClientSize().GetWidth() - GetRowLabelSize();
+
 		for (col = 0 ; col < nCols ; col++)
 		{
 			colName = thread->DataSet()->ColName(col);
@@ -228,14 +234,8 @@ void ctlSQLResult::DisplayData(bool single)
 			colTypes.Add(colType);
 			colTypClasses.Add(thread->DataSet()->ColTypClass(col));
 
-			wxString colHeader = colName + wxT("\n") + colType;
+			sumWidth += GetColSize(col);
 
-			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 +246,25 @@ void ctlSQLResult::DisplayData(bool single)
 				SetColAttr(col, attr);
 			}
 		}
+		
+		if (sumWidth > availWidth)
+		{
+			// Seek for extra-wide columns and shrink them to some reasonable limit.
+			//   Say, half(?) the available width
+			maxWidth = availWidth / 2;
+			for (col = 0 ; col < nCols ; col++)
+			{
+				oldWidth = GetColSize(col);
+				if (oldWidth > maxWidth)
+				{
+					sumWidth -= oldWidth;
+					// If the rest of columns are short, make sure to use all remaining space for this wide column
+					newWidth = wxMax(maxWidth, availWidth - sumWidth);
+					SetColSize(col, newWidth);
+					sumWidth += newWidth;
+				}
+			}
+		}
 	}
 	Thaw();
 }
