### Install Dependencies with Yarn Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/CONTRIBUTING.md Installs all project dependencies required for development. This command should be run after cloning the repository. ```bash yarn ``` -------------------------------- ### Install SQL Formatter via yarn Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/README.md This snippet demonstrates how to install the SQL Formatter library using yarn, an alternative package manager for JavaScript. This command achieves the same result as the npm installation. ```sh yarn add sql-formatter ``` -------------------------------- ### SQL Query Example Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/static/index.html An example of a SQL query that can be formatted by the SQL Formatter. This demonstrates a common structure involving joins, subqueries, filtering, and ordering. ```sql select supplier_name,city from (select * from suppliers join addresses on suppliers.address_id=addresses.id) as suppliers where supplier_id>500 order by supplier_name asc,city desc; ``` -------------------------------- ### SQL Formatter CLI Help and Version Source: https://context7.com/sql-formatter-org/sql-formatter/llms.txt Display help information or check the version of the `sql-formatter` command-line tool. Use `--help` to see all available options and `--version` to check the installed version. ```bash # Get help sql-formatter --help # Check version sql-formatter --version ``` -------------------------------- ### Install SQL Formatter via npm Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/README.md This snippet shows how to install the SQL Formatter library using npm, the Node Package Manager. This is the primary method for adding the library to your JavaScript project. ```sh npm install sql-formatter ``` -------------------------------- ### SQL Standard Indentation Style Example Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/docs/indentStyle.md Demonstrates the standard indentation style for SQL code. This style indents code based on the 'tabWidth' configuration. ```sql SELECT COUNT(a.column1), MAX(b.column2 + b.column3), b.column4 AS four FROM ( SELECT column1, column5 FROM table1 ) a JOIN table2 b ON a.column5 = b.column5 WHERE column6 AND column7 GROUP BY column4 ``` -------------------------------- ### Example SQL Code for Formatting Tests Source: https://github.com/sql-formatter-org/sql-formatter/wiki/Formatting This snippet contains various SQL statements including SELECT, INSERT, UPDATE, and CREATE TABLE. It is used to test the effectiveness of different SQL formatting tools and to demonstrate common SQL syntax. ```sql SELECT supplier_name, city -- inline comment ,(select count(*) from people where supplier_id = s.id) as sup_count FROM suppliers s left join addresses a on s.address_id=a.id WHERE s.value>500 and a.city = 'New York' ORDER BY supplier_name asc,city desc; /* another comment in here */ INSERT INTO articles (title, author, submission_date) VALUES ('Learn SQL', 'John Doe', now()); UPDATE articles SET author = 'Peter', submission_date = '2022-01-01' WHERE title like '%by Peter'; CREATE TABLE articles ( id int not null auto_increment, title varchar(100) not null, author varchar(40) not null, submission_date date, primary key ( id ) ); ``` -------------------------------- ### Untitled No description -------------------------------- ### SQL Formatter CLI Configuration JSON Example Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/README.md This JSON object represents a configuration file for the SQL Formatter CLI. It specifies formatting options such as the SQL language dialect, tab width, keyword casing, and the number of lines between queries. ```json { "language": "spark", "tabWidth": 2, "keywordCase": "upper", "linesBetweenQueries": 2 } ``` -------------------------------- ### Standard SQL Comments: Single-line and Multi-line Source: https://github.com/sql-formatter-org/sql-formatter/wiki/Comments Demonstrates the standard SQL syntax for single-line comments (starting with '--') and multi-line block comments (enclosed in '/* */'). These are universally supported across SQL dialects. ```sql -- single line comment /* multi line block comment */ ``` -------------------------------- ### Configure SQL Formatter Options in JavaScript Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/README.md This JavaScript example illustrates how to pass configuration options to the `sql-formatter` library's `format` function. Options include specifying the SQL language dialect, tab width, keyword casing, and lines between queries. ```javascript format('SELECT * FROM tbl', { language: 'spark', tabWidth: 2, keywordCase: 'upper', linesBetweenQueries: 2, }); ``` -------------------------------- ### Configure paramTypes for Positional and Named Placeholders Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/docs/paramTypes.md An example JavaScript configuration object for 'paramTypes'. This specific configuration enables '?' positional placeholders and both ':' and '@' for named placeholders, while disabling default numbered placeholders. ```javascript { positional: true, numbered: [], named: [':', '@'], } ``` -------------------------------- ### PostgreSQL ALTER TABLE - Basic Table Modifications Source: https://github.com/sql-formatter-org/sql-formatter/wiki/ALTER-TABLE Provides examples for common ALTER TABLE operations in PostgreSQL, such as renaming columns, constraints, and tables. It also includes schema changes and partition management. ```sql ALTER TABLE [IF EXISTS] [ONLY] name ["*"] alter_table_action ["," ...] ALTER TABLE ALL IN TABLESPACE name [OWNED BY role_name ["," ...]] SET TABLESPACE new_tablespace [NOWAIT] alter_table_action: RENAME [ COLUMN ] column_name TO new_column_name | RENAME CONSTRAINT constraint_name TO new_constraint_name | RENAME TO new_name | SET SCHEMA new_schema | ATTACH PARTITION partition_name { FOR VALUES partition_bound_spec | DEFAULT } | DETACH PARTITION partition_name [ CONCURRENTLY | FINALIZE ] ``` -------------------------------- ### SQL Standard Frame Definition Syntax Source: https://github.com/sql-formatter-org/sql-formatter/wiki/WINDOW-clause Defines the structure for specifying the frame (subset of rows) within a window partition, including units, start, and exclusion. ```sql frame_definition: frame_units {frame_start | frame_between} [frame_exclusion] frame_units: ROWS | RANGE frame_start: UNBOUNDED PRECEDING | CURRENT ROW | unsigned_value PRECEDING frame_between: BETWEEN frame_bound AND frame_bound frame_bound: frame_start | UNBOUNDED FOLLOWING | unsigned_value FOLLOWING frame_exclusion: EXCLUDE CURRENT ROW | EXCLUDE GROUP | EXCLUDE TIES | EXCLUDE NO OTHERS ``` -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### Define Custom Parameter Syntax with String.raw Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/docs/paramTypes.md An alternative method to define custom parameter syntax using `String.raw` to avoid double-escaping backslashes in the regex. This achieves the same result as the previous example but with potentially cleaner syntax. ```javascript { custom: [ { regex: String.raw`{[a-zA-Z0-9_]+}`, }, ], } ``` -------------------------------- ### Define Custom Parameter Syntax with Regex Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/docs/paramTypes.md Demonstrates how to define a custom parameter syntax using a regular expression within the 'paramTypes' configuration. This example targets parameters enclosed in curly braces, like '{name}'. ```javascript { custom: [ { regex: '\{[a-zA-Z0-9_]+\}', }, ], } ``` -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### Push Demo Page to GitHub Pages Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/CONTRIBUTING.md Pushes the demo page content to the `gh-pages` branch of the origin remote using git subtree. This is part of the publish flow for the demo site. ```bash git subtree push --prefix static origin gh-pages ``` -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### SQL Tabular Left Indentation Style Example Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/docs/indentStyle.md Illustrates the 'tabularLeft' indentation style for SQL code. This style uses a fixed 10-space indent and aligns keywords to the left, ignoring the 'tabWidth' setting. ```sql SELECT COUNT(a.column1), MAX(b.column2 + b.column3), b.column4 AS four FROM ( SELECT column1, column5 FROM table1 ) a JOIN table2 b ON a.column5 = b.column5 WHERE column6 AND column7 GROUP BY column4 ``` -------------------------------- ### Untitled No description -------------------------------- ### SQL Formatter CLI Usage - Help Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/README.md This shell command invokes the SQL Formatter CLI tool with the help flag (`-h`), displaying its usage instructions and available options. It shows how to specify input files, output files, SQL dialect, and configuration. ```sh sql-formatter -h ``` -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### SQL Tabular Right Indentation Style Example Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/docs/indentStyle.md Shows the 'tabularRight' indentation style for SQL code. This style also uses a fixed 10-space indent but aligns keywords to the right, disregarding the 'tabWidth' setting. ```sql SELECT COUNT(a.column1), MAX(b.column2 + b.column3), b.column4 AS four FROM ( SELECT column1, column5 FROM table1 ) a JOIN table2 b ON a.column5 = b.column5 WHERE column6 AND column7 GROUP BY column4 ``` -------------------------------- ### Release New Version (npm) Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/CONTRIBUTING.md Bumps the version, creates a git tag, prepares a git release, and publishes to npm. This command requires admin access and is specifically for npm, not Yarn. ```bash npm run release ``` -------------------------------- ### Format SQL via Command Line (stdin, files, stdout) Source: https://context7.com/sql-formatter-org/sql-formatter/llms.txt Format SQL code using the `sql-formatter` command-line interface. Supports reading from standard input, processing files, and outputting to standard output or a specified file. Multiple SQL dialects can be specified using the `-l` flag. ```bash # Format from stdin echo "SELECT * FROM users WHERE id=1" | sql-formatter -l mysql # Format a file and output to stdoutsql-formatter -l postgresql input.sql # Format and write to output filesql-formatter -l bigquery input.sql -o formatted.sql # In-place formattingsql-formatter --fix -l sqlite query.sql ``` -------------------------------- ### SQL Standard CREATE TABLE Syntax Source: https://github.com/sql-formatter-org/sql-formatter/wiki/CREATE-TABLE This snippet shows the basic CREATE TABLE syntax as defined by the SQL standard. It outlines the core structure for creating tables, which forms the basis for most dialectal variations. ```sql CREATE [{GLOBAL | LOCAL} TEMPORARY] TABLE ``` -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### Run Tests with Yarn Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/CONTRIBUTING.md Executes all defined tests for the project. New features and bug fixes should be accompanied by new tests. Language-specific tests are in `sqldialect.test.ts` and general tests in `behavesLikeSqlFormatter.ts`. ```bash yarn test ``` -------------------------------- ### SingleStoreDB CREATE TABLE Syntax Variations Source: https://github.com/sql-formatter-org/sql-formatter/wiki/CREATE-TABLE Presents the CREATE TABLE syntax for SingleStoreDB. This includes options for rowstore tables, various temporary table types, and the IF NOT EXISTS clause. ```sql CREATE [ROWSTORE] [REFERENCE | TEMPORARY | GLOBAL TEMPORARY] TABLE [IF NOT EXISTS] ``` -------------------------------- ### Configure SQL Formatter with JSON (CLI) Source: https://context7.com/sql-formatter-org/sql-formatter/llms.txt Configure the `sql-formatter` CLI using a JSON configuration file (e.g., `.sql-formatter.json`) or inline JSON options. This allows for specifying language, tab width, keyword casing, and other formatting rules. ```bash # Using configuration file (.sql-formatter.json) # Create .sql-formatter.json: # { # "language": "mysql", # "tabWidth": 4, # "keywordCase": "upper", # "linesBetweenQueries": 2 # } sql-formatter input.sql # Using inline JSON configuration sql-formatter -c '{"language":"postgresql","keywordCase":"upper","tabWidth":4}' query.sql ``` -------------------------------- ### Untitled No description -------------------------------- ### SingleStoreDB CREATE VIEW Syntax Variations Source: https://github.com/sql-formatter-org/sql-formatter/wiki/CREATE-VIEW SingleStoreDB's CREATE VIEW syntax allows specifying the definer and schema binding options. ```sql CREATE [DEFINER "" {user | CURRENT_USER}] [SCHEMA_BINDING "" {ON | OFF}] VIEW ``` -------------------------------- ### Untitled No description -------------------------------- ### Format SQL with Specific Dialects in JavaScript Source: https://context7.com/sql-formatter-org/sql-formatter/llms.txt Demonstrates importing and using specific SQL dialect formatters for different database systems like BigQuery, PostgreSQL, MySQL, SQLite, Transact-SQL, and Snowflake. It also shows using the general `format()` function with a language string for bundled dialects. ```javascript import { format, formatDialect, bigquery, postgresql, mysql, sqlite, transactsql, snowflake } from 'sql-formatter'; // BigQuery with specific syntax const bqResult = formatDialect( 'SELECT * FROM `project.dataset.table` WHERE id=@id', { dialect: bigquery } ); // PostgreSQL with JSON operators const pgResult = formatDialect( "SELECT data->>'name' as name FROM users WHERE data @> '{\"active\":true}'", { dialect: postgresql } ); // MySQL with backtick identifiers const mysqlResult = formatDialect( 'SELECT `user`.`id`, `user`.`name` FROM `users` AS `user`', { dialect: mysql } ); // SQLite with specific functions const sqliteResult = formatDialect( 'SELECT datetime("now"), julianday("now") FROM data', { dialect: sqlite } ); // Transact-SQL with square brackets const tsqlResult = formatDialect( 'SELECT [user].[id] FROM [dbo].[users] WHERE [active]=1', { dialect: transactsql } ); // Snowflake with warehouse-specific syntax const snowflakeResult = formatDialect( 'SELECT * FROM table1 AT(TIMESTAMP => '2023-01-01'::TIMESTAMP)', { dialect: snowflake } ); // Using format() with language string (all dialects bundled) const result = format('SELECT * FROM data', { language: 'trino' // or 'spark', 'hive', 'redshift', 'db2', etc. }); ``` -------------------------------- ### Untitled No description -------------------------------- ### BigQuery CREATE TABLE Syntax Variations Source: https://github.com/sql-formatter-org/sql-formatter/wiki/CREATE-TABLE Illustrates the CREATE TABLE syntax specific to Google BigQuery. This includes options for replacing existing tables and defining temporary, snapshot, or external tables. ```sql CREATE [OR REPLACE] [TEMP | TEMPORARY | SNAPSHOT | EXTERNAL] TABLE [IF NOT EXISTS] ``` -------------------------------- ### Untitled No description -------------------------------- ### Trino CREATE TABLE Syntax Variations Source: https://github.com/sql-formatter-org/sql-formatter/wiki/CREATE-TABLE Shows the CREATE TABLE syntax for Trino. This basic syntax includes the option to use IF NOT EXISTS for safe table creation. ```sql CREATE TABLE [IF NOT EXISTS] ``` -------------------------------- ### Format SQL from Stdin using CLI Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/README.md This shell command demonstrates piping SQL input to the SQL Formatter CLI. The tool reads from standard input (`stdin`) and outputs the formatted SQL to standard output (`stdout`). ```sh echo 'select * from tbl where id = 3' | sql-formatter ``` -------------------------------- ### Format Multiple SQL Queries with Spacing in JavaScript Source: https://context7.com/sql-formatter-org/sql-formatter/llms.txt Illustrates how to format multiple SQL queries within a single string using the `format` function. It demonstrates controlling the spacing between queries, from the default one line to two lines or no lines at all, and also shows keyword casing. ```javascript import { format } from 'sql-formatter'; // Default spacing (1 line between queries) const defaultSpacing = format( 'SELECT * FROM users; SELECT * FROM orders; SELECT * FROM products;', { language: 'sql' } ); console.log(defaultSpacing); // Output: // SELECT // * // FROM // users; // // SELECT // * // FROM // orders; // // SELECT // * // FROM // products; // Two lines between queries const doubleSpacing = format( 'DELETE FROM temp_table; INSERT INTO logs VALUES (1, "cleanup"); SELECT COUNT(*) FROM logs;', { language: 'mysql', linesBetweenQueries: 2, keywordCase: 'upper' } ); console.log(doubleSpacing); // Output: // DELETE FROM temp_table; // // // INSERT INTO logs // VALUES // (1, "cleanup"); // // // SELECT // COUNT(*) // FROM // logs; // No lines between queries const noSpacing = format( 'SELECT 1; SELECT 2; SELECT 3;', { language: 'sql', linesBetweenQueries: 0 } ); console.log(noSpacing); // Output: // SELECT // 1; // SELECT // 2; // SELECT // 3; ``` -------------------------------- ### Untitled No description -------------------------------- ### Untitled No description -------------------------------- ### SQL Standard CREATE VIEW Syntax Source: https://github.com/sql-formatter-org/sql-formatter/wiki/CREATE-VIEW The standard SQL CREATE VIEW syntax, as defined by SQL-2008, specifies the basic structure for creating views. This serves as a baseline for understanding variations in different database systems. ```sql CREATE [RECURSIVE] VIEW ``` -------------------------------- ### DuckDB: ASOF and POSITIONAL JOIN Support Source: https://github.com/sql-formatter-org/sql-formatter/wiki/FROM-clause Explains DuckDB's additional join types: ASOF JOIN, which uses syntax similar to NATURAL JOIN for time-series data, and POSITIONAL JOIN. ```sql -- DuckDB supports ASOF JOIN and POSITIONAL JOIN. -- ASOF JOIN syntax is similar to NATURAL JOIN: SELECT * FROM tableA ASOF JOIN tableB ON tableA.time = tableB.time; -- POSITIONAL JOIN example (conceptual): SELECT * FROM tableA POSITIONAL JOIN tableB; ``` -------------------------------- ### SQL Standard Window Specification Syntax Source: https://github.com/sql-formatter-org/sql-formatter/wiki/WINDOW-clause Defines the components of a window specification, including partitioning, ordering, and frame definition. ```sql window_specification: [identifier] [PARTITION BY { column [COLLATE collation] } ["," ...]] [ORDER BY sort_specification_list] [frame_definition] ``` -------------------------------- ### SQL Array Literals Syntax Source: https://github.com/sql-formatter-org/sql-formatter/wiki/Arrays-and-Maps Demonstrates the different syntaxes for defining array literals in SQL. This includes the common bracket notation and the ARRAY keyword. Support varies across SQL dialects. ```sql SELECT [1, "two", 3]; SELECT ARRAY[1, 2, 3]; ``` -------------------------------- ### Format SQL Query using JavaScript Library Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/README.md This JavaScript snippet shows the basic usage of the `sql-formatter` library to format a SQL query. It imports the `format` function and calls it with a SQL string and language option. The output is a formatted SQL string. ```javascript import { format } from 'sql-formatter'; console.log(format('SELECT * FROM tbl', { language: 'mysql' })); ``` -------------------------------- ### Replace Placeholders in SQL Statements with JavaScript Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/README.md This JavaScript code snippet shows how the `sql-formatter` library can be used to replace placeholders (like '?') in prepared SQL statements. The `params` option takes an array of values to substitute. ```javascript format('SELECT * FROM tbl WHERE foo = ?', { params: ["'bar'"], }); ``` -------------------------------- ### PL/SQL CREATE TABLE Syntax Variations Source: https://github.com/sql-formatter-org/sql-formatter/wiki/CREATE-TABLE Illustrates the CREATE TABLE syntax within PL/SQL, Oracle's procedural extension. It showcases the diverse table types supported, including various temporary and blockchain table definitions. ```sql CREATE [table_type] TABLE table_type: {GLOBAL | PRIVATE} TEMPORARY | SHARDED | DUPLICATED | [IMMUTABLE] BLOCKCHAIN | IMMUTABLE ``` -------------------------------- ### Untitled No description -------------------------------- ### SQL Formatting with Custom Named Parameters Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/docs/paramTypes.md Illustrates the SQL output after applying the 'paramTypes' configuration for custom named parameters. The formatter correctly recognizes and retains the ':name' syntax. ```sql SELECT * FROM users WHERE name = :name AND age < :age ``` -------------------------------- ### DuckDB CREATE TABLE Syntax Variations Source: https://github.com/sql-formatter-org/sql-formatter/wiki/CREATE-TABLE Presents the CREATE TABLE syntax for DuckDB. This syntax includes options for replacing tables and defining temporary tables, along with the standard IF NOT EXISTS clause. ```sql CREATE [OR REPLACE] [TEMP | TEMPORARY] TABLE [IF NOT EXISTS] ``` -------------------------------- ### Redshift CREATE TABLE Syntax Variations Source: https://github.com/sql-formatter-org/sql-formatter/wiki/CREATE-TABLE Shows the CREATE TABLE syntax for Amazon Redshift. This syntax supports local temporary tables and includes the IF NOT EXISTS option. ```sql CREATE [[LOCAL] {TEMPORARY | TEMP}] TABLE [IF NOT EXISTS] ``` -------------------------------- ### Untitled No description -------------------------------- ### PostgreSQL CREATE TABLE Syntax Variations Source: https://github.com/sql-formatter-org/sql-formatter/wiki/CREATE-TABLE Details the CREATE TABLE syntax for PostgreSQL. This includes options for temporary (local/global), unlogged tables, and the IF NOT EXISTS clause. ```sql CREATE [[GLOBAL | LOCAL] {TEMPORARY | TEMP} | UNLOGGED] TABLE [IF NOT EXISTS] ``` -------------------------------- ### Format with Default Prepared Statement Syntax (PostgreSQL) Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/docs/paramTypes.md Demonstrates formatting a SQL query with default PostgreSQL numbered parameters ('$1', '$2'). This requires no special configuration as it aligns with the default syntax. ```typescript format('SELECT * FROM users WHERE name = $1 AND age < $2', { language: 'postgresql' }); ``` -------------------------------- ### Format SQL with Specific Dialect Imports - JavaScript Source: https://context7.com/sql-formatter-org/sql-formatter/llms.txt Formats SQL queries by importing specific dialects like PostgreSQL or MySQL using the `formatDialect` function. This approach is useful for optimizing bundle size by including only the necessary dialect definitions. It allows for precise formatting tailored to specific SQL database systems. ```javascript import { formatDialect, postgresql, mysql, sqlite } from 'sql-formatter'; // PostgreSQL with specific dialect import const pgResult = formatDialect( 'SELECT * FROM users WHERE id=$1 AND email=$2', { dialect: postgresql } ); console.log(pgResult); // MySQL with custom configuration const mysqlResult = formatDialect( 'SELECT `user_name`,`email` FROM `users` WHERE `id` IN (1,2,3)', { dialect: mysql, keywordCase: 'upper', expressionWidth: 50 } ); console.log(mysqlResult); ``` -------------------------------- ### Format SQL with Custom Dialect Configuration (TypeScript) Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/docs/dialect.md Demonstrates how to format SQL using a custom dialect configuration. This feature is experimental and the `DialectOptions` interface may change. It allows for fine-grained control over tokenization and formatting rules, intended for advanced users or when forking the library is the only alternative. ```typescript import { formatDialect, DialectOptions } from 'sql-formatter'; const myDialect: DialectOptions { name: 'my_dialect', tokenizerOptions: { // See source code for examples of tokenizer config options // For example: src/languages/sqlite/sqlite.formatter.ts }, formatOptions: { // ... }, }; const result = formatDialect('SELECT * FROM tbl', { dialect: myDialect }); ``` -------------------------------- ### Trino CREATE VIEW Syntax Variations Source: https://github.com/sql-formatter-org/sql-formatter/wiki/CREATE-VIEW Trino's CREATE VIEW syntax supports replacing views and creating materialized views. ```sql CREATE [OR REPLACE] [MATERIALIZED] VIEW ``` -------------------------------- ### SingleStoreDB and TiDB ORDER BY Clause Syntax Source: https://github.com/sql-formatter-org/sql-formatter/wiki/ORDER-BY-clause SingleStoreDB and TiDB implement a straightforward ORDER BY clause, allowing ordering by expressions with optional ASC/DESC. ```sql ORDER BY {expr [ASC | DESC]} ["," ...] ``` -------------------------------- ### Transact-SQL CREATE TABLE Syntax Source: https://github.com/sql-formatter-org/sql-formatter/wiki/CREATE-TABLE Provides the basic CREATE TABLE syntax for Microsoft SQL Server's Transact-SQL. This is a fundamental syntax without many of the dialect-specific modifiers found elsewhere. ```sql CREATE TABLE ``` -------------------------------- ### Format SQL Queries with Dialect and Options - JavaScript Source: https://context7.com/sql-formatter-org/sql-formatter/llms.txt Formats SQL queries using the `format` function with specified language dialect and various configuration options. It can handle basic formatting and advanced scenarios with options like tab width, keyword casing, and line breaks. This function is a core part of the library for general SQL formatting. ```javascript import { format } from 'sql-formatter'; // Basic formatting with dialect const result = format('SELECT * FROM users WHERE id=1 AND active=true', { language: 'mysql' }); console.log(result); // Advanced formatting with multiple options const advancedResult = format( 'SELECT user_id,COUNT(*),SUM(amount) FROM orders WHERE status="completed" GROUP BY user_id', { language: 'postgresql', tabWidth: 4, keywordCase: 'upper', dataTypeCase: 'upper', functionCase: 'upper', linesBetweenQueries: 2, denseOperators: false } ); console.log(advancedResult); ``` -------------------------------- ### PostgreSQL ALTER TABLE - Inheritance, Ownership, and Identity Source: https://github.com/sql-formatter-org/sql-formatter/wiki/ALTER-TABLE Illustrates how to manage table inheritance, ownership, and replica identity in PostgreSQL using ALTER TABLE. This includes setting tablespace, logging, storage parameters, and OIDs. ```sql alter_table_action: SET WITHOUT OIDS | SET TABLESPACE new_tablespace | SET { LOGGED | UNLOGGED } | SET ( storage_parameter [= value] [, ... ] ) | RESET ( storage_parameter [, ... ] ) | INHERIT parent_table | NO INHERIT parent_table | OF type_name | NOT OF | OWNER TO { new_owner | CURRENT_ROLE | CURRENT_USER | SESSION_USER } | REPLICA IDENTITY { DEFAULT | USING INDEX index_name | FULL | NOTHING } ``` -------------------------------- ### Apply Joins in PL/SQL and Transact-SQL Source: https://github.com/sql-formatter-org/sql-formatter/wiki/FROM-clause Illustrates the support for APPLY joins, specifically CROSS APPLY and OUTER APPLY, in PL/SQL and Transact-SQL. These joins allow for table-valued functions to be applied on a row-by-row basis from the left side of the join. ```sql -- PL/SQL and Transact-SQL support for APPLY joins -- Example (conceptual): SELECT * FROM tableA CROSS APPLY tableB_function(tableA.id); SELECT * FROM tableA OUTER APPLY tableC_function(tableA.id); ``` -------------------------------- ### SQL Templating Syntax Workaround Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/README.md Offers a workaround for SQL Formatter failing to parse templating syntax. By using the `paramTypes` configuration option with a custom regex, templating constructs can be treated as prepared-statement parameter placeholders, enabling formatting for common templating use cases. ```javascript format('SELECT {col1}, {col2} FROM {tablename};', { paramTypes: { custom: [{ regex: String.raw`{\w+}` }] }, }); ``` -------------------------------- ### Handling Webpack Module Parse Errors Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/README.md Provides solutions for 'Module parse failed: Unexpected token' errors when bundling with Webpack. These errors often stem from Babel not supporting class properties syntax. Recommended fixes include updating Babel/Webpack, switching to `@babel/preset-env`, or including the `@babel/plugin-proposal-class-properties` plugin. ```javascript // Example of class properties syntax that might cause issues export default class ExpressionFormatter { inline = false; } ``` -------------------------------- ### Hive CREATE TABLE Syntax Variations Source: https://github.com/sql-formatter-org/sql-formatter/wiki/CREATE-TABLE Shows the CREATE TABLE syntax specific to Apache Hive. It highlights the support for temporary, external tables, and the IF NOT EXISTS clause for safe table creation. ```sql CREATE [TEMPORARY] [EXTERNAL] TABLE [IF NOT EXISTS] ``` -------------------------------- ### PL/SQL CREATE VIEW Syntax Variations Source: https://github.com/sql-formatter-org/sql-formatter/wiki/CREATE-VIEW PL/SQL supports creating standard views and materialized views, with options for replacing views, enforcing editions, and forcing creation. ```sql CREATE [OR REPLACE] [[NO] FORCE] [EDITIONING | EDITIONABLE [EDITIONING] | NONEDITIONABLE] VIEW ``` ```sql CREATE MATERIALIZED VIEW ``` -------------------------------- ### DuckDB CREATE VIEW Syntax Variations Source: https://github.com/sql-formatter-org/sql-formatter/wiki/CREATE-VIEW DuckDB's CREATE VIEW syntax allows for replacing views, creating temporary views, and conditional creation with IF NOT EXISTS. ```sql CREATE [OR REPLACE] [TEMP | TEMPORARY] VIEW [IF NOT EXISTS] ``` -------------------------------- ### MariaDB CREATE TABLE Syntax Variations Source: https://github.com/sql-formatter-org/sql-formatter/wiki/CREATE-TABLE Details the CREATE TABLE syntax for MariaDB. This includes options for replacing tables, creating temporary tables, and using the IF NOT EXISTS clause to prevent errors. ```sql CREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS] ``` -------------------------------- ### MySQL CREATE VIEW Syntax Variations Source: https://github.com/sql-formatter-org/sql-formatter/wiki/CREATE-VIEW MySQL's CREATE VIEW syntax includes options for replacing views, specifying algorithm, definer, and SQL security. ```sql CREATE [OR REPLACE] [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}] [DEFINER = user] [SQL SECURITY { DEFINER | INVOKER }] VIEW ``` -------------------------------- ### MySQL CREATE TABLE Syntax Variations Source: https://github.com/sql-formatter-org/sql-formatter/wiki/CREATE-TABLE Presents the CREATE TABLE syntax for MySQL. This variation primarily focuses on the support for temporary tables and the IF NOT EXISTS clause. ```sql CREATE [TEMPORARY] TABLE [IF NOT EXISTS] ``` -------------------------------- ### DB2i ORDER BY Clause Syntax Source: https://github.com/sql-formatter-org/sql-formatter/wiki/ORDER-BY-clause DB2i's ORDER BY clause syntax, similar to DB2, it supports 'INPUT SEQUENCE' and ordering by sort specifications, with an option to include 'SIBLINGS'. ```sql ORDER [SIBLINGS] BY INPUT SEQUENCE ``` ```sql ORDER [SIBLINGS] BY sort_specification [ {"," sort_specification}... ] ``` ```sql sort_specification: ORDER OF table_name | expr [ASC | DESC] [NULLS FIRST | NULLS LAST] ``` -------------------------------- ### MariaDB, MySQL, TiDB, SingleStoreDB: STRAIGHT_JOIN Support Source: https://github.com/sql-formatter-org/sql-formatter/wiki/FROM-clause Notes that MariaDB, MySQL, TiDB, and SingleStoreDB support the STRAIGHT_JOIN syntax. This hint influences the join order, forcing the left table to be joined first. ```sql -- Example using STRAIGHT_JOIN (MariaDB, MySQL, TiDB, SingleStoreDB): SELECT * FROM tableA STRAIGHT_JOIN tableB ON tableA.id = tableB.id; ``` -------------------------------- ### SQL Indentation with Tabs using useTabs: true Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/docs/useTabs.md This code snippet demonstrates how SQL code is formatted when the 'useTabs' option is set to true. It showcases the indentation structure achieved using tab characters, providing an alternative to space-based indentation. The 'tabWidth' option is relevant when 'useTabs' is false. ```sql SELECT *, FROM ( SELECT column1, column5 FROM table1 ) a JOIN table2 WHERE column6 AND column7 GROUP BY column4 ``` -------------------------------- ### Define Custom Parameter Syntax with Key Function Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/docs/paramTypes.md Shows how to provide a `key` function within the `custom` parameter type configuration. This function extracts the actual parameter name from the matched text, allowing for cleaner parameter substitution. ```javascript { custom: [ { regex: String.raw`{[a-zA-Z0-9_]+}`, key: (text) => text.slice(1, -1), // discard first and last char }, ], } ``` -------------------------------- ### Control SQL Indentation Source: https://context7.com/sql-formatter-org/sql-formatter/llms.txt Configure indentation style and width for formatted SQL output. Options include 'tabWidth' for the number of spaces (default is 2) and 'useTabs' to use tabs instead of spaces. This feature is part of the 'sql-formatter' library. ```javascript import { format } from 'sql-formatter'; // Default 2-space indentation const defaultIndent = format( 'SELECT * FROM (SELECT id, name FROM users) AS u JOIN orders ON u.id=orders.user_id', { language: 'sql' } ); console.log(defaultIndent); // 4-space indentation const fourSpaceIndent = format( 'SELECT * FROM (SELECT id, name FROM users) AS u JOIN orders ON u.id=orders.user_id', { language: 'sql', tabWidth: 4 } ); console.log(fourSpaceIndent); // Tab indentation const tabIndent = format( 'SELECT * FROM (SELECT id FROM users) AS u', { language: 'sql', useTabs: true } ); console.log(tabIndent); ``` -------------------------------- ### Standard SQL FROM Clause Syntax Source: https://github.com/sql-formatter-org/sql-formatter/wiki/FROM-clause Defines the basic structure of a FROM clause in standard SQL, including table references and joined tables. This syntax forms the foundation for most SQL dialects, though specific join types and specifications may vary. ```sql FROM table_reference ["," ...] table_reference: table_factor | joined_table joined_table: table_reference CROSS JOIN table_reference | table_reference [join_type] JOIN table_reference [join_specification] | table_reference NATURAL [join_type] JOIN table_reference join_type: INNER | {LEFT | RIGHT | FULL} [OUTER] join_specification: ON expr | USING "(" identifier ["," ...] ")" ``` -------------------------------- ### Untitled No description -------------------------------- ### Format SQL with Positional Placeholders (JavaScript) Source: https://github.com/sql-formatter-org/sql-formatter/blob/master/docs/params.md Formats an SQL query using positional placeholders ('?'). Requires an array of strings for the 'params' option. The values are directly substituted into the query. ```javascript format('SELECT * FROM persons WHERE fname = ? AND age = ?', { params: ["'John'", '27'], language: 'sql' }); ``` -------------------------------- ### Snowflake CREATE TABLE Syntax Variations Source: https://github.com/sql-formatter-org/sql-formatter/wiki/CREATE-TABLE Details the CREATE TABLE syntax for Snowflake. This syntax supports temporary (local/global) and volatile/transient tables, along with the IF NOT EXISTS clause and options for replacing tables. ```sql CREATE [OR REPLACE] [table_type] TABLE [IF NOT EXISTS] table_type: [LOCAL | GLOBAL] {TEMP | TEMPORARY} | VOLATILE | TRANSIENT ``` -------------------------------- ### Untitled No description -------------------------------- ### SQLite CREATE TABLE Syntax Variations Source: https://github.com/sql-formatter-org/sql-formatter/wiki/CREATE-TABLE Presents the CREATE TABLE syntax for SQLite. This variation focuses on the support for temporary tables and the IF NOT EXISTS clause. ```sql CREATE [TEMPORARY | TEMP] TABLE [IF NOT EXISTS] ``` -------------------------------- ### N1QL SELECT Syntax Source: https://github.com/sql-formatter-org/sql-formatter/wiki/SELECT-clause N1QL (for Couchbase) SELECT syntax, which allows for optional hint comments before the ALL or DISTINCT keywords. ```sql SELECT [hint_comment] [ALL | DISTINCT] ``` -------------------------------- ### Untitled No description