private void addResultsTab(ResultTab tab, IResultTab resultTabToReplace) {
    if (null == resultTabToReplace && null == _stickyTab) {
      _tabbedExecutionsPanel.addTab(tab.getTitle(), null, tab, tab.getViewableSqlString());
      checkResultTabLimit();
    } else {
      if (null != resultTabToReplace && _session.getProperties().getKeepTableLayoutOnRerun()) {
        TableState sortableTableState = resultTabToReplace.getResultSortableTableState();
        if (null != sortableTableState) {
          tab.applyResultSortableTableState(sortableTableState);
        }
      }

      int indexToReplace = -1;
      ImageIcon tabIcon = null;

      // Either resultTabToReplace or _stickyTab must be not null here
      if (null != resultTabToReplace && _stickyTab != resultTabToReplace) {
        indexToReplace = getIndexOfTab(resultTabToReplace);
      } else {
        indexToReplace = getIndexOfTab(_stickyTab);
        if (-1 == indexToReplace) {
          // sticky tab was closed
          _stickyTab = null;
        } else {
          tabIcon = getStickyIcon();
          _stickyTab = tab;
        }
      }

      if (-1 == indexToReplace) {
        // Just add the tab
        addResultsTab(tab, null);
        return;
      }

      closeTabAt(indexToReplace);
      _tabbedExecutionsPanel.insertTab(
          tab.getTitle(), tabIcon, tab, tab.getViewableSqlString(), indexToReplace);
    }
  }