PostgreSQL: Print CREATE TABLE clauses in PostgreSQL order
diff --git a/src/ast/ddl.rs b/src/ast/ddl.rs
index e2cc004..2162461 100644
--- a/src/ast/ddl.rs
+++ b/src/ast/ddl.rs
@@ -49,9 +49,9 @@
     HiveRowFormat, HiveSetLocation, Ident, InitializeKind, MySQLColumnPosition, ObjectName,
     OnCommit, OneOrManyWithParens, OperateFunctionArg, OrderByExpr, ProjectionSelect, Query,
     RefreshModeKind, ResetConfig, RowAccessPolicy, SequenceOptions, Spanned, SqlOption, Statement,
-    StorageLifecyclePolicy, StorageSerializationPolicy, TableVersion, Tag, TriggerEvent,
-    TriggerExecBody, TriggerObject, TriggerPeriod, TriggerReferencing, Value, ValueWithSpan,
-    WrappedCollection,
+    StorageLifecyclePolicy, StorageSerializationPolicy, StorageType, TableVersion,
+    TablespaceOption, Tag, TriggerEvent, TriggerExecBody, TriggerObject, TriggerPeriod,
+    TriggerReferencing, Value, ValueWithSpan, WrappedCollection,
 };
 use crate::display_utils::{DisplayCommaSeparated, Indent, NewLine, SpaceOrNewline};
 use crate::keywords::Keyword;
@@ -3086,6 +3086,10 @@
     /// ClickHouse "ON COMMIT" clause:
     /// <https://clickhouse.com/docs/en/sql-reference/statements/create/table/>
     pub on_commit: Option<OnCommit>,
+    /// `TABLESPACE` clause.
+    /// <https://www.postgresql.org/docs/current/sql-createtable.html>
+    /// <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
+    pub tablespace: Option<TablespaceOption>,
     /// ClickHouse "ON CLUSTER" clause:
     /// <https://clickhouse.com/docs/en/sql-reference/distributed-ddl/>
     pub on_cluster: Option<Ident>,
@@ -3391,8 +3395,7 @@
         }
 
         match &self.table_options {
-            options @ CreateTableOptions::With(_)
-            | options @ CreateTableOptions::Plain(_)
+            options @ CreateTableOptions::Plain(_)
             | options @ CreateTableOptions::TableProperties(_) => write!(f, " {options}")?,
             _ => (),
         }
@@ -3409,6 +3412,9 @@
         if let Some(partition_by) = self.partition_by.as_ref() {
             write!(f, " PARTITION BY {partition_by}")?;
         }
+        if let options @ CreateTableOptions::With(_) = &self.table_options {
+            write!(f, " {options}")?;
+        }
         if let Some(cluster_by) = self.cluster_by.as_ref() {
             write!(f, " CLUSTER BY {cluster_by}")?;
         }
@@ -3526,6 +3532,14 @@
             };
             write!(f, " {on_commit}")?;
         }
+        if let Some(TablespaceOption { name, storage }) = &self.tablespace {
+            write!(f, " TABLESPACE {name}")?;
+            match storage {
+                Some(StorageType::Disk) => f.write_str(" STORAGE DISK")?,
+                Some(StorageType::Memory) => f.write_str(" STORAGE MEMORY")?,
+                None => (),
+            }
+        }
         if let Some(backup) = self.backup {
             write!(f, " BACKUP {}", if backup { "YES" } else { "NO" })?;
         }
diff --git a/src/ast/helpers/stmt_create_table.rs b/src/ast/helpers/stmt_create_table.rs
index 4ab9ac2..221d2c6 100644
--- a/src/ast/helpers/stmt_create_table.rs
+++ b/src/ast/helpers/stmt_create_table.rs
@@ -29,7 +29,8 @@
     DistStyle, Expr, FileFormat, ForValues, HiveDistributionStyle, HiveFormat, Ident,
     InitializeKind, ObjectName, OnCommit, OneOrManyWithParens, Query, RefreshModeKind,
     RowAccessPolicy, SqliteTableOptions, Statement, StorageLifecyclePolicy,
-    StorageSerializationPolicy, TableConstraint, TableVersion, Tag, WithData, WrappedCollection,
+    StorageSerializationPolicy, TableConstraint, TableVersion, TablespaceOption, Tag, WithData,
+    WrappedCollection,
 };
 
 use crate::parser::ParserError;
@@ -115,6 +116,8 @@
     pub comment: Option<CommentDef>,
     /// Optional `ON COMMIT` behavior.
     pub on_commit: Option<OnCommit>,
+    /// Optional `TABLESPACE` clause.
+    pub tablespace: Option<TablespaceOption>,
     /// Optional cluster identifier.
     pub on_cluster: Option<Ident>,
     /// Optional primary key expression.
@@ -223,6 +226,7 @@
             version: None,
             comment: None,
             on_commit: None,
+            tablespace: None,
             on_cluster: None,
             primary_key: None,
             order_by: None,
@@ -384,6 +388,11 @@
         self.on_commit = on_commit;
         self
     }
+    /// Set the `TABLESPACE` clause.
+    pub fn tablespace(mut self, tablespace: Option<TablespaceOption>) -> Self {
+        self.tablespace = tablespace;
+        self
+    }
     /// Set cluster identifier for the table.
     pub fn on_cluster(mut self, on_cluster: Option<Ident>) -> Self {
         self.on_cluster = on_cluster;
@@ -617,6 +626,7 @@
             version: self.version,
             comment: self.comment,
             on_commit: self.on_commit,
+            tablespace: self.tablespace,
             on_cluster: self.on_cluster,
             primary_key: self.primary_key,
             order_by: self.order_by,
@@ -702,6 +712,7 @@
             version: table.version,
             comment: table.comment,
             on_commit: table.on_commit,
+            tablespace: table.tablespace,
             on_cluster: table.on_cluster,
             primary_key: table.primary_key,
             order_by: table.order_by,
@@ -751,6 +762,7 @@
     pub cluster_by: Option<WrappedCollection<Vec<Expr>>>,
     pub inherits: Option<Vec<ObjectName>>,
     pub table_options: CreateTableOptions,
+    pub tablespace: Option<TablespaceOption>,
 }
 
 #[cfg(test)]
diff --git a/src/ast/spans.rs b/src/ast/spans.rs
index e89d575..c13be41 100644
--- a/src/ast/spans.rs
+++ b/src/ast/spans.rs
@@ -616,6 +616,7 @@
             clone,
             comment: _, // todo, no span
             on_commit: _,
+            tablespace: _,   // todo, no span
             on_cluster: _,   // todo, clickhouse specific
             primary_key: _,  // todo, clickhouse specific
             order_by: _,     // todo, clickhouse specific
diff --git a/src/parser/mod.rs b/src/parser/mod.rs
index d523b48..9487b7c 100644
--- a/src/parser/mod.rs
+++ b/src/parser/mod.rs
@@ -9405,6 +9405,11 @@
             None
         };
 
+        let mut tablespace = create_table_config.tablespace;
+        if tablespace.is_none() {
+            tablespace = self.parse_optional_tablespace_option()?;
+        }
+
         // Redshift: BACKUP YES|NO
         let backup = if self.parse_keyword(Keyword::BACKUP) {
             let keyword = self.expect_one_of_keywords(&[Keyword::YES, Keyword::NO])?;
@@ -9476,6 +9481,7 @@
             .comment_after_column_def(comment_after_column_def)
             .order_by(order_by)
             .on_commit(on_commit)
+            .tablespace(tablespace)
             .on_cluster(on_cluster)
             .clustered_by(clustered_by)
             .partition_by(partition_by)
@@ -9705,6 +9711,16 @@
             None
         };
 
+        let partition_by_dialect =
+            dialect_of!(self is BigQueryDialect | PostgreSqlDialect | GenericDialect);
+        // PostgreSQL orders `PARTITION BY` before `WITH (...)`.
+        let mut partition_by =
+            if partition_by_dialect && self.parse_keywords(&[Keyword::PARTITION, Keyword::BY]) {
+                Some(Box::new(self.parse_expr()?))
+            } else {
+                None
+            };
+
         // PostgreSQL supports `WITH ( options )`, before `AS`
         let with_options = self.parse_options(Keyword::WITH)?;
         if !with_options.is_empty() {
@@ -9715,13 +9731,12 @@
         if !table_properties.is_empty() {
             table_options = CreateTableOptions::TableProperties(table_properties);
         }
-        let partition_by = if dialect_of!(self is BigQueryDialect | PostgreSqlDialect | GenericDialect)
+        if partition_by.is_none()
+            && partition_by_dialect
             && self.parse_keywords(&[Keyword::PARTITION, Keyword::BY])
         {
-            Some(Box::new(self.parse_expr()?))
-        } else {
-            None
-        };
+            partition_by = Some(Box::new(self.parse_expr()?));
+        }
 
         let mut cluster_by = None;
         if dialect_of!(self is BigQueryDialect | GenericDialect) {
@@ -9739,8 +9754,19 @@
             };
         }
 
+        let mut tablespace = None;
         if !dialect_of!(self is HiveDialect) && table_options == CreateTableOptions::None {
             let plain_options = self.parse_plain_options()?;
+            let plain_options: Vec<SqlOption> = plain_options
+                .into_iter()
+                .filter_map(|option| match option {
+                    SqlOption::TableSpace(option) => {
+                        tablespace = Some(option);
+                        None
+                    }
+                    other => Some(other),
+                })
+                .collect();
             if !plain_options.is_empty() {
                 table_options = CreateTableOptions::Plain(plain_options)
             }
@@ -9751,6 +9777,7 @@
             cluster_by,
             inherits,
             table_options,
+            tablespace,
         })
     }
 
@@ -9814,40 +9841,8 @@
         }
 
         // <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
-        if self.parse_keywords(&[Keyword::TABLESPACE]) {
-            let _ = self.consume_token(&Token::Eq);
-            let value = self.next_token();
-
-            let tablespace = match value.token {
-                Token::Word(Word { value: name, .. }) | Token::SingleQuotedString(name) => {
-                    let storage = match self.parse_keyword(Keyword::STORAGE) {
-                        true => {
-                            let _ = self.consume_token(&Token::Eq);
-                            let storage_token = self.next_token();
-                            match &storage_token.token {
-                                Token::Word(w) => match w.value.to_uppercase().as_str() {
-                                    "DISK" => Some(StorageType::Disk),
-                                    "MEMORY" => Some(StorageType::Memory),
-                                    _ => self
-                                        .expected("Storage type (DISK or MEMORY)", storage_token)?,
-                                },
-                                _ => self.expected("Token::Word", storage_token)?,
-                            }
-                        }
-                        false => None,
-                    };
-
-                    Ok(Some(SqlOption::TableSpace(TablespaceOption {
-                        name,
-                        storage,
-                    })))
-                }
-                _ => {
-                    return self.expected("Token::Word", value)?;
-                }
-            };
-
-            return tablespace;
+        if let Some(option) = self.parse_optional_tablespace_option()? {
+            return Ok(Some(SqlOption::TableSpace(option)));
         }
 
         // <https://dev.mysql.com/doc/refman/8.4/en/create-table.html>
@@ -9952,6 +9947,45 @@
         }))
     }
 
+    /// Parse the `TABLESPACE` clause, returning the parsed option when present.
+    ///
+    /// [MySQL](https://dev.mysql.com/doc/refman/8.4/en/create-table.html)
+    /// [PostgreSQL](https://www.postgresql.org/docs/current/sql-createtable.html)
+    fn parse_optional_tablespace_option(
+        &mut self,
+    ) -> Result<Option<TablespaceOption>, ParserError> {
+        if !self.parse_keywords(&[Keyword::TABLESPACE]) {
+            return Ok(None);
+        }
+        let _ = self.consume_token(&Token::Eq);
+        let value = self.next_token();
+
+        match value.token {
+            Token::Word(Word { value: name, .. }) | Token::SingleQuotedString(name) => {
+                let storage = match self.parse_keyword(Keyword::STORAGE) {
+                    true => {
+                        let _ = self.consume_token(&Token::Eq);
+                        let storage_token = self.next_token();
+                        match &storage_token.token {
+                            Token::Word(w) => match w.value.to_uppercase().as_str() {
+                                "DISK" => Some(StorageType::Disk),
+                                "MEMORY" => Some(StorageType::Memory),
+                                _ => {
+                                    self.expected("Storage type (DISK or MEMORY)", storage_token)?
+                                }
+                            },
+                            _ => self.expected("Token::Word", storage_token)?,
+                        }
+                    }
+                    false => None,
+                };
+
+                Ok(Some(TablespaceOption { name, storage }))
+            }
+            _ => self.expected("Token::Word", value)?,
+        }
+    }
+
     /// Parse plain options.
     pub fn parse_plain_options(&mut self) -> Result<Vec<SqlOption>, ParserError> {
         let mut options = Vec::new();
diff --git a/tests/sqlparser_duckdb.rs b/tests/sqlparser_duckdb.rs
index 216d514..248493a 100644
--- a/tests/sqlparser_duckdb.rs
+++ b/tests/sqlparser_duckdb.rs
@@ -758,6 +758,7 @@
             clone: Default::default(),
             comment: Default::default(),
             on_commit: Default::default(),
+            tablespace: Default::default(),
             on_cluster: Default::default(),
             primary_key: Default::default(),
             order_by: Default::default(),
diff --git a/tests/sqlparser_mssql.rs b/tests/sqlparser_mssql.rs
index 4b9b4cf..38efd78 100644
--- a/tests/sqlparser_mssql.rs
+++ b/tests/sqlparser_mssql.rs
@@ -1938,6 +1938,7 @@
                 clone: None,
                 comment: None,
                 on_commit: None,
+                tablespace: None,
                 on_cluster: None,
                 primary_key: None,
                 order_by: None,
@@ -2118,6 +2119,7 @@
                 clone: None,
                 comment: None,
                 on_commit: None,
+                tablespace: None,
                 on_cluster: None,
                 primary_key: None,
                 order_by: None,
diff --git a/tests/sqlparser_mysql.rs b/tests/sqlparser_mysql.rs
index d5ba2a9..a8f94de 100644
--- a/tests/sqlparser_mysql.rs
+++ b/tests/sqlparser_mysql.rs
@@ -1086,11 +1086,14 @@
 fn parse_create_table_with_all_table_options() {
     let sql =
         "CREATE TABLE foo (bar INT NOT NULL AUTO_INCREMENT) ENGINE = InnoDB AUTO_INCREMENT = 123 DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci INSERT_METHOD = FIRST KEY_BLOCK_SIZE = 8 ROW_FORMAT = DYNAMIC DATA DIRECTORY = '/var/lib/mysql/data' INDEX DIRECTORY = '/var/lib/mysql/index' PACK_KEYS = 1 STATS_AUTO_RECALC = 1 STATS_PERSISTENT = 0 STATS_SAMPLE_PAGES = 128 DELAY_KEY_WRITE = 1 COMPRESSION = 'ZLIB' ENCRYPTION = 'Y' MAX_ROWS = 10000 MIN_ROWS = 10 AUTOEXTEND_SIZE = 64 AVG_ROW_LENGTH = 128 CHECKSUM = 1 CONNECTION = 'mysql://localhost' ENGINE_ATTRIBUTE = 'primary' PASSWORD = 'secure_password' SECONDARY_ENGINE_ATTRIBUTE = 'secondary_attr' START TRANSACTION TABLESPACE my_tablespace STORAGE DISK UNION = (table1, table2, table3)";
+    let rendered =
+        "CREATE TABLE foo (bar INT NOT NULL AUTO_INCREMENT) ENGINE = InnoDB AUTO_INCREMENT = 123 DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci INSERT_METHOD = FIRST KEY_BLOCK_SIZE = 8 ROW_FORMAT = DYNAMIC DATA DIRECTORY = '/var/lib/mysql/data' INDEX DIRECTORY = '/var/lib/mysql/index' PACK_KEYS = 1 STATS_AUTO_RECALC = 1 STATS_PERSISTENT = 0 STATS_SAMPLE_PAGES = 128 DELAY_KEY_WRITE = 1 COMPRESSION = 'ZLIB' ENCRYPTION = 'Y' MAX_ROWS = 10000 MIN_ROWS = 10 AUTOEXTEND_SIZE = 64 AVG_ROW_LENGTH = 128 CHECKSUM = 1 CONNECTION = 'mysql://localhost' ENGINE_ATTRIBUTE = 'primary' PASSWORD = 'secure_password' SECONDARY_ENGINE_ATTRIBUTE = 'secondary_attr' START TRANSACTION UNION = (table1, table2, table3) TABLESPACE my_tablespace STORAGE DISK";
 
-    match mysql().verified_stmt(sql) {
+    match mysql().one_statement_parses_to(sql, rendered) {
         Statement::CreateTable(CreateTable {
             name,
             table_options,
+            tablespace,
             ..
         }) => {
             assert_eq!(name, vec![Ident::new("foo".to_owned())].into());
@@ -1199,11 +1202,12 @@
             assert!(plain_options.contains(&SqlOption::Ident(
                 Ident::new("START TRANSACTION".to_owned()).into()
             )));
-            assert!(
-                plain_options.contains(&SqlOption::TableSpace(TablespaceOption {
+            assert_eq!(
+                tablespace,
+                Some(TablespaceOption {
                     name: "my_tablespace".to_string(),
                     storage: Some(StorageType::Disk),
-                }))
+                })
             );
 
             assert!(plain_options.contains(&SqlOption::NamedParenthesizedList(
diff --git a/tests/sqlparser_postgres.rs b/tests/sqlparser_postgres.rs
index 9f85cd0..493e1e5 100644
--- a/tests/sqlparser_postgres.rs
+++ b/tests/sqlparser_postgres.rs
@@ -7453,6 +7453,7 @@
             clone: None,
             comment: None,
             on_commit: None,
+            tablespace: None,
             on_cluster: None,
             primary_key: None,
             order_by: None,
@@ -12291,3 +12292,115 @@
         );
     }
 }
+
+#[test]
+fn parse_create_table_inherits_with_clause_order() {
+    let sql = "CREATE TABLE m2 (CHECK (x > 0)) INHERITS (m) WITH (autovacuum_enabled = off)";
+    match pg_and_generic().verified_stmt(sql) {
+        Statement::CreateTable(CreateTable {
+            inherits,
+            table_options,
+            tablespace,
+            ..
+        }) => {
+            assert_eq_vec(&["m"], &inherits.as_ref().unwrap()[0].0);
+            assert!(matches!(table_options, CreateTableOptions::With(_)));
+            assert!(tablespace.is_none());
+        }
+        _ => unreachable!(),
+    }
+}
+
+#[test]
+fn parse_create_table_partition_by_tablespace_clause_order() {
+    let sql = "CREATE TABLE p (a INT) PARTITION BY LIST(a) TABLESPACE ts";
+    match pg_and_generic().verified_stmt(sql) {
+        Statement::CreateTable(CreateTable {
+            partition_by,
+            tablespace,
+            ..
+        }) => {
+            assert!(partition_by.is_some());
+            assert_eq!(
+                tablespace,
+                Some(TablespaceOption {
+                    name: "ts".to_string(),
+                    storage: None,
+                })
+            );
+        }
+        _ => unreachable!(),
+    }
+}
+
+#[test]
+fn parse_create_table_inherits_partition_with_on_commit_tablespace_clause_order() {
+    let sql = "CREATE TABLE t (a INT) INHERITS (m) PARTITION BY LIST(a) WITH (autovacuum_enabled = off) ON COMMIT DROP TABLESPACE ts";
+    match pg_and_generic().verified_stmt(sql) {
+        Statement::CreateTable(CreateTable {
+            inherits,
+            partition_by,
+            table_options,
+            on_commit,
+            tablespace,
+            ..
+        }) => {
+            assert_eq_vec(&["m"], &inherits.as_ref().unwrap()[0].0);
+            assert!(partition_by.is_some());
+            assert!(matches!(table_options, CreateTableOptions::With(_)));
+            assert!(matches!(on_commit, Some(OnCommit::Drop)));
+            assert_eq!(
+                tablespace,
+                Some(TablespaceOption {
+                    name: "ts".to_string(),
+                    storage: None,
+                })
+            );
+        }
+        _ => unreachable!(),
+    }
+}
+
+#[test]
+fn parse_create_table_with_before_partition_by_clause_order() {
+    pg_and_generic().one_statement_parses_to(
+        "CREATE TABLE t (a INT) INHERITS (m) WITH (autovacuum_enabled = off) PARTITION BY LIST(a) ON COMMIT DROP TABLESPACE ts",
+        "CREATE TABLE t (a INT) INHERITS (m) PARTITION BY LIST(a) WITH (autovacuum_enabled = off) ON COMMIT DROP TABLESPACE ts",
+    );
+}
+
+#[test]
+fn parse_create_table_as_tablespace_clause_order() {
+    let sql = "CREATE TABLE t TABLESPACE ts AS SELECT a FROM t2";
+    match pg_and_generic().verified_stmt(sql) {
+        Statement::CreateTable(CreateTable {
+            query, tablespace, ..
+        }) => {
+            assert!(query.is_some());
+            assert_eq!(
+                tablespace,
+                Some(TablespaceOption {
+                    name: "ts".to_string(),
+                    storage: None,
+                })
+            );
+        }
+        _ => unreachable!(),
+    }
+}
+
+#[test]
+fn parse_create_table_tablespace_clause_order_errors() {
+    assert!(matches!(
+        pg_and_generic().parse_sql_statements("CREATE TABLE t (a INT) TABLESPACE"),
+        Err(ParserError::ParserError(_))
+    ));
+    assert!(matches!(
+        pg_and_generic().parse_sql_statements("CREATE TABLE t (a INT) TABLESPACE ts STORAGE"),
+        Err(ParserError::ParserError(_))
+    ));
+    assert!(matches!(
+        pg_and_generic().parse_sql_statements("CREATE TABLE t (a INT) ON COMMIT DROP TABLESPACE"),
+        Err(ParserError::ParserError(_))
+    ));
+}