Ora

How do I arrange SQL code in Notepad++?

Published in SQL Formatting 6 mins read

Arranging SQL code in Notepad++ significantly enhances readability and maintainability, allowing for easier collaboration and debugging. You can format SQL code effectively using Notepad++'s built-in Find & Replace with regular expressions, or by leveraging powerful plugins for automated, more sophisticated formatting.

Why Format Your SQL Code?

Well-formatted SQL code is crucial for several reasons:

  • Improved Readability: Clearly structured code is easier to read and understand, reducing cognitive load.
  • Easier Debugging: When statements are properly aligned, issues like missing commas or incorrect clauses become immediately apparent.
  • Enhanced Collaboration: Consistent formatting makes it easier for multiple developers to work on the same codebase without introducing stylistic conflicts.
  • Maintainability: Future modifications and updates become simpler when the code structure is logical and predictable.

Manual SQL Formatting with Notepad++'s Find & Replace (Regex)

Notepad++'s Find & Replace feature, combined with regular expressions, offers a powerful way to implement basic SQL formatting. Here’s how to apply specific formatting rules:

  1. Open the Find/Replace Dialog: Press Ctrl + H.
  2. Set Search Mode: Ensure "Regular expression" is selected under the "Search Mode" section.
  3. Understand Regex Characters:
    • \s+: Matches one or more whitespace characters (spaces, tabs, newlines).
    • \s*: Matches zero or more whitespace characters.
    • \n: Represents a newline character.
    • \t: Represents a tab character.
    • ( and ): Create a capturing group.
    • $ followed by a number (e.g., $1): Refers to the content of a capturing group.

Step 1: Formatting the SELECT Clause

To ensure each selected column begins on a new line and is indented, you first need to format the SELECT keyword itself. This involves moving SELECT and its initial columns. A more precise method is to move the SELECT keyword to its own line (if it's not already) and then handle subsequent elements.

  • Action: Replace SELECT followed by any whitespace with SELECT, a new line, and a tab.

  • Find What: SELECT\s+ (This finds "SELECT" followed by one or more whitespace characters.)

  • Replace With: SELECT\n\t (This replaces it with "SELECT", a new line, and then a tab character for indentation.)

  • Example:

    -- Before
    SELECT col1, col2 FROM table;
    
    -- After applying this step (and assuming other steps follow)
    SELECT
        col1, col2 FROM table;

    Note: This specific step ensures SELECT starts on a fresh line and the first item is tabbed. Subsequent steps will handle other commas.

Step 2: Arranging Columns After Commas

This step ensures that every item in a list (like selected columns) starts on a new line and is indented after a comma.

  • Action: Replace a comma followed by any whitespace with a comma, a new line, and a tab.

  • Find What: ,\s* (This finds a comma followed by zero or more whitespace characters.)

  • Replace With: ,\n\t (This replaces it with a comma, a new line, and then a tab character for consistent indentation.)

  • Example:

    -- Before
    SELECT col1, col2, col3 FROM table;
    
    -- After applying this step (and assuming Step 1 was applied)
    SELECT
        col1,
        col2,
        col3 FROM table;

Step 3: Placing the FROM Clause on a New Line

This step moves the FROM clause to its own dedicated line for better readability.

  • Action: Replace any whitespace followed by FROM with a new line before FROM.

  • Find What: \s+FROM (This finds one or more whitespace characters immediately preceding "FROM".)

  • Replace With: \nFROM (This replaces the whitespace with a new line before the "FROM" keyword.)

  • Example:

    -- Before
    SELECT
        col1,
        col2
    FROM table;
    
    -- After applying this step
    SELECT
        col1,
        col2
    FROM
        table;

Important Notes for Regex Find & Replace:

  • Case Sensitivity: Notepad++'s regex engine can be case-sensitive. If your SQL keywords might be in mixed case (e.g., select, SELECT, Select), you might need to use (SELECT|select) in your regex or check the "Match case" option if you want strict matching.
  • Scope: You can choose to replace in the "Current document" or "All opened documents."
  • Testing: Always test your regex on a small, disposable piece of code first to ensure it behaves as expected before applying it to critical files.

Enhancing SQL Readability with Plugins

For more advanced and automated SQL formatting, Notepad++ plugins are highly recommended. They often provide more comprehensive rule sets and one-click formatting.

Poor Man's T-SQL Formatter

This popular plugin is excellent for formatting T-SQL (Microsoft SQL Server dialect) but can also handle generic SQL quite well.

  • Features: Indentation, casing (keywords, identifiers), newline placement, and more.
  • Installation:
    1. Go to Plugins > Plugins Admin... in Notepad++.
    2. Search for "Poor Man's T-SQL Formatter".
    3. Check the box next to it and click "Install".
    4. Restart Notepad++ if prompted.
  • Usage: After installation, select your SQL code (or place your cursor in the document) and go to Plugins > Poor Man's T-SQL Formatter > Format T-SQL or use the keyboard shortcut Ctrl + K.
  • Configuration: The plugin offers options to customize formatting styles, accessible through its menu.
  • Resource: Poor Man's T-SQL Formatter GitHub

Using External Formatters with NppExec

For maximum flexibility, you can integrate external SQL formatters (like those written in Python or Node.js) into Notepad++ using the NppExec plugin.

  • Concept: NppExec allows you to execute external commands or scripts directly from Notepad++. You can set up a script to send your current SQL file to an external formatter and then display the formatted output back in Notepad++.
  • Installation: Install NppExec via Plugins > Plugins Admin....
  • Example (using a hypothetical sql-formatter command-line tool):
    1. Install an external SQL formatter (e.g., npm install -g sql-formatter if you have Node.js).
    2. In Notepad++, go to Plugins > NppExec > Execute... (F6).
    3. Enter a command like:
      NPP_SAVE
      sql-formatter "$(FULL_CURRENT_PATH)" > "$(FULL_CURRENT_PATH).formatted"
      NPP_OPEN "$(FULL_CURRENT_PATH).formatted"
    4. You can save this script and assign a shortcut to it. This example saves the current file, formats it into a new file, and then opens the formatted file. A more advanced script could replace the content of the current file directly.
  • Resource: NppExec Plugin Page

Essential Notepad++ Features for SQL Development

Beyond formatting, Notepad++ offers other features that greatly aid SQL development:

SQL Syntax Highlighting

Notepad++ automatically highlights SQL keywords, strings, and comments, making your code easier to read.

  • How to Enable: Ensure your file is saved with a .sql extension, or manually select Language > SQL from the Notepad++ menu.

Code Folding

This feature allows you to collapse sections of your code (like large subqueries or stored procedures) to focus on specific parts.

  • Usage: Click the minus signs (-) in the left margin next to code blocks to collapse them.

Best Practices for Clean SQL Code

Adopting consistent practices alongside formatting tools will ensure your SQL code remains impeccable:

  • Consistent Casing: Decide on a casing standard (e.g., UPPERCASE for keywords, lowercase for object names) and stick to it.
  • Meaningful Aliases: Use clear and concise aliases for tables and columns to improve readability, especially in complex joins.
  • Comments: Add comments (-- for single line, /* */ for multi-line) to explain complex logic, business rules, or non-obvious parts of your queries.
  • Whitespace: Use spaces and newlines generously to separate logical blocks of code.

By combining Notepad++'s built-in functionalities with powerful plugins and best practices, you can maintain a clean, readable, and highly efficient SQL codebase.