Sensible page breaks in LaTeX grouped longtables

2021-08-31

I had a longtable in a LaTeX document that was grouped, with multirow items and midrules which delimited the groups. The problem was that when the table broke across two pages, the groups were split and the multirow was not repeated on the second page, making the table look very messy. For example:

A messy grouped longtable

I learned this trick from the longtable documentation that can be used to prevent the table breaking at certain lines. Simply use the * variant of \\, i.e. \\*, on all lines where the table isn’t allowed to break, and it will only break at the end of a group. For example:

\begin{longtable}{ccc}
\caption{A better looking table} \\ 
	\toprule
{X} & {Y} & {Value} \\
	\midrule
	\endfirsthead
	\toprule
{X} & {Y} & {Value} \\
	\midrule
	\endhead
{\multirow{4}{*}{A}} & {\multirow{4}{*}{A}} & 1 \\*
   &  & 2 \\*
   &  & 3 \\*
   &  & 4 \\
   \midrule
{\multirow{4}{*}{A}} & {\multirow{4}{*}{B}} & 1 \\*
   &  & 2 \\*
   &  & 3 \\*
   &  & 4 \\
   \midrule
{\multirow{4}{*}{A}} & {\multirow{4}{*}{C}} & 1 \\*
   &  & 2 \\*
   &  & 3 \\*
   &  & 4 \\
   \midrule
{\multirow{4}{*}{A}} & {\multirow{4}{*}{D}} & 1 \\*
   &  & 2 \\*
   &  & 3 \\*
   &  & 4 \\
   \bottomrule
\end{longtable}

which produces this much prettier looking table:

a cleaner grouped longtable