diff --git a/src/tools/gen_keywordlist.pl b/src/tools/gen_keywordlist.pl
index bb03dbb..0d55697 100644
--- a/src/tools/gen_keywordlist.pl
+++ b/src/tools/gen_keywordlist.pl
@@ -62,34 +62,6 @@ my $base_filename = $1 . '_d';
 my $kw_def_file = $output_path . $base_filename . '.h';
 
 open(my $kif, '<', $kw_input_file) || die "$kw_input_file: $!\n";
-open(my $kwdef, '>', $kw_def_file) || die "$kw_def_file: $!\n";
-
-# Opening boilerplate for keyword definition header.
-printf $kwdef <<EOM, $base_filename, uc $base_filename, uc $base_filename;
-/*-------------------------------------------------------------------------
- *
- * %s.h
- *    List of keywords represented as a ScanKeywordList.
- *
- * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
- * Portions Copyright (c) 1994, Regents of the University of California
- *
- * NOTES
- *  ******************************
- *  *** DO NOT EDIT THIS FILE! ***
- *  ******************************
- *
- *  It has been GENERATED by src/tools/gen_keywordlist.pl
- *
- *-------------------------------------------------------------------------
- */
-
-#ifndef %s_H
-#define %s_H
-
-#include "common/kwlookup.h"
-
-EOM
 
 # Parse input file for keyword names.
 my @keywords;
@@ -124,6 +96,37 @@ for my $i (0 .. $#keywords - 1)
 	  if ($keywords[$i] cmp $keywords[ $i + 1 ]) >= 0;
 }
 
+# Validate the input before opening the output, so invalid keywords cannot
+# truncate an existing header or leave a partial new one.
+open(my $kwdef, '>', $kw_def_file) || die "$kw_def_file: $!\n";
+
+# Opening boilerplate for keyword definition header.
+printf $kwdef <<EOM, $base_filename, uc $base_filename, uc $base_filename;
+/*-------------------------------------------------------------------------
+ *
+ * %s.h
+ *    List of keywords represented as a ScanKeywordList.
+ *
+ * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
+ * Portions Copyright (c) 1994, Regents of the University of California
+ *
+ * NOTES
+ *  ******************************
+ *  *** DO NOT EDIT THIS FILE! ***
+ *  ******************************
+ *
+ *  It has been GENERATED by src/tools/gen_keywordlist.pl
+ *
+ *-------------------------------------------------------------------------
+ */
+
+#ifndef %s_H
+#define %s_H
+
+#include "common/kwlookup.h"
+
+EOM
+
 # Emit the string containing all the keywords.
 
 printf $kwdef qq|static const char %s_kw_string[] =\n\t"|, $varname;
