Writing custom queries for the CodeQL CLI

You can write your own CodeQL queries to find specific vulnerabilities and errors.

This article is specifically about writing queries to use with the database analyze command to produce interpreted results. For conceptual information about custom queries, see Custom CodeQL queries.

Writing a valid query

Before running a custom analysis you need to write a valid query, and save it in a file with a .ql extension. There is extensive documentation available to help you write queries. For more information, see CodeQL queries.

Including query metadata

When running queries with the database analyze command, you must include the following two properties to ensure that the results are interpreted correctly:

For more information about these metadata properties, see Metadata for CodeQL queries and the Query metadata style guide.

Including query help for custom CodeQL queries in SARIF files

For information about query help and documentation formats, see Custom CodeQL queries.

To include query help in SARIF files when running code scanning analyses:

  1. Write your query help in one of the following formats:

  2. Run codeql database analyze with the --sarif-add-query-help option:

    codeql database analyze <database> --format=sarif-latest --output=results.sarif --sarif-add-query-help
    

    Note

    The --sarif-add-query-help option is available from CodeQL CLI v2.7.1 onwards.

  3. Upload the SARIF file to GitHub.

Next steps

To share and use your custom queries, see Publishing and using CodeQL packs.