{"id":15170733,"url":"https://github.com/charlesstover/mssql-query-builder","last_synced_at":"2025-10-01T05:30:54.696Z","repository":{"id":32701450,"uuid":"140608236","full_name":"CharlesStover/mssql-query-builder","owner":"CharlesStover","description":"Dynamically build Microsoft SQL Server queries using JavaScript.","archived":true,"fork":false,"pushed_at":"2022-04-14T14:11:34.000Z","size":87,"stargazers_count":4,"open_issues_count":3,"forks_count":2,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-10-01T06:31:52.702Z","etag":null,"topics":["chai","es6","javascript","js","mocha","mssql","node","nodejs","npm","npm-module","npm-package","npmjs","sql","sql-server","sqlserver","travis","travis-ci","travisci","ts","typescript"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/mssql-query-builder","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/CharlesStover.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-07-11T17:28:30.000Z","updated_at":"2024-02-26T08:09:16.000Z","dependencies_parsed_at":"2022-08-07T18:00:51.730Z","dependency_job_id":null,"html_url":"https://github.com/CharlesStover/mssql-query-builder","commit_stats":null,"previous_names":["quisido/mssql-query-builder","charlesstover/mssql-query-builder"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/CharlesStover%2Fmssql-query-builder","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/CharlesStover%2Fmssql-query-builder/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/CharlesStover%2Fmssql-query-builder/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/CharlesStover%2Fmssql-query-builder/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/CharlesStover","download_url":"https://codeload.github.com/CharlesStover/mssql-query-builder/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":234827057,"owners_count":18892884,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["chai","es6","javascript","js","mocha","mssql","node","nodejs","npm","npm-module","npm-package","npmjs","sql","sql-server","sqlserver","travis","travis-ci","travisci","ts","typescript"],"created_at":"2024-09-27T08:22:32.880Z","updated_at":"2025-10-01T05:30:54.345Z","avatar_url":"https://github.com/CharlesStover.png","language":"TypeScript","readme":"# SQLServer Query Builder [![Tweet](https://img.shields.io/twitter/url/http/shields.io.svg?style=social)](https://twitter.com/intent/tweet?text=Dynamically%20build%20Microsoft%20SQL%20Server%20queries%20in%20JavaScript,%20using%20the%20NPM%20package%20mssql-query-builder!\u0026url=https://github.com/CharlesStover/mssql-query-builder\u0026via=CharlesStover\u0026hashtags=javascript,sql,sqlserver,typescript,webdev,webdevelopment)\n\nDynamically build Microsoft SQL Server queries using JavaScript.\n\n[![version](https://img.shields.io/npm/v/mssql-query-builder.svg)](https://www.npmjs.com/package/mssql-query-builder)\n[![minified size](https://img.shields.io/bundlephobia/min/mssql-query-builder.svg)](https://www.npmjs.com/package/mssql-query-builder)\n[![minzipped size](https://img.shields.io/bundlephobia/minzip/mssql-query-builder.svg)](https://www.npmjs.com/package/mssql-query-builder)\n[![downloads](https://img.shields.io/npm/dt/mssql-query-builder.svg)](https://www.npmjs.com/package/mssql-query-builder)\n[![build](https://travis-ci.com/CharlesStover/mssql-query-builder.svg)](https://travis-ci.com/CharlesStover/mssql-query-builder/)\n\n## Install\n\n* `npm install mssql-query-builder --save` or\n* `yarn add mssql-query-builder`\n\n## Use\n\nNote: All methods can be chained together. Each method call returns the original QueryBuilder instance.\n\n```JS\nimport QueryBuilder from 'mssql-query-builder';\n\n// Provide an optional MSSQL_CONFIG parameter to include server, user, password, database, etc.\n// If you do not include one, it will default to environment variables.\nconst query = new QueryBuilder(MSSQL_CONFIG);\n\n// Seed the query builder with some literal SQL.\nquery.query('SELECT a WHERE b = c');\n\n// Conditionally write part of the query.\nquery.from(\n  process.env.flag ?\n    'table_x' :\n    'table_y'\n);\n\nif (today === 'Monday') {\n  query.whereIn('birthDay', [ 1, 2, 3 ]);\n}\n\n// Skip the first 100 rows, then fetch the next 25.\n// Useful for pagination.\nquery.offset(100).fetch(25);\n\n// Output the query thus far as a string (for debugging).\nconsole.log(query.buildQuery());\n\n// Execute the query (returns a Promise).\nquery.execute().then(\n  (result) =\u003e {\n    console.log(result);\n  }\n);\n```\n\n## Methods\n\n### all(all?: boolean)\n\nSpecifies that duplicate rows can appear in the result set.\n\nThis is the opposite of `distinct(boolean)`.\n\n### distinct(distinct?: boolean)\n\nSpecifies that only unique rows can appear in the result set.\n\nNull values are considered equal for the purposes of the DISTINCT keyword.\n\n### distinct(selectItem: string)\n\nReturns all distinct values of the single select item.\n\n### distinct(selectList: string[])\n\nReturns all distinct values of the select list.\n\n### execute()\n\nExecutes the query as built thus far. Returns a Promise of a result.\n\n### execute(query: string)\n\nExecutes the query string provided. Returns a Promise of a result.\n\n### fetch(n: number)\n\nSpecifies the number of rows to return, after processing the OFFSET clause.\n\nThe argument for the FETCH clause can be an integer or expression that is greater than or equal to one.\n\n### from(table: string)\n\nSpecifies the tables from which to retrieve rows.\n\n### groupBy(column: string)\n\nSpecifies the groups (equivalence classes) that output rows are to be placed in.\n\nIf aggregate functions are included in the SELECT clause's select list, the GROUP BY clause calculates a summary value for each group.\n\n### having(...having: string[])\n\nSpecifies a search condition for a group or an aggregate. HAVING can be used only with the SELECT statement. HAVING is typically used with a GROUP BY clause. When GROUP BY is not used, there is an implicit single, aggregated group.\n\n### input(value: Input)\n\nInputs a SQL variable and returns its generated variable name.\n\n```JS\nconst myVar = query.input('Bob');\nquery.where('name = ' + myVar); // WHERE name = @__QB_INPUT_1__\n```\n\n### input(value: Input, name: string, type: ISqlTypeFactoryWithNoParams)\n\nInputs a SQL variable.\n\n```JS\nquery\n  .input(1, 'myNumber', Int)\n  .input('password', 'userPass', NVarChar)\n```\n\nSupported `Input` types and their respective `ISqlTypeFactoryWithNoParams` types are are boolean (Bit), number (Int), string (NVarChar), Buffer (VarBinary), and Date (DateTime).\n\nOmitting the `ISqlTypeFactoryWithNoParams` type will result in the QueryBuilder determining the type on its own.\n\n### inputBit and inputBoolean(value: boolean, name: string)\n\nInputs a boolean SQL variable. Shorthand for `input(value, name, Bit)`.\n\n### inputBuffer and inputVarBinary(value: Buffer, name: string)\n\nInputs a Buffer SQL variable. Shorthand for `input(value, name, VarBinary)`.\n\n### inputDate and inputDateTime(value: Date, name: string)\n\nInputs a Date SQL variable. Shorthand for `input(value, name, DateTime)`.\n\n### inputInt and inputNumber(value: number, name: string)\n\nInputs a number SQL variable. Shorthand for `input(value, name, Int)`.\n\n### inputNVarChar and inputString(value: string, name: string)\n\nInputs a string SQL variable. Shorthand for `input(value, name, NVarChar)`.\n\n### offset(n: number)\n\nSpecifies the number of rows to skip, before starting to return rows from the query expression.\n\nThe argument for the OFFSET clause can be an integer or expression that is greater than or equal to zero.\n\n### orderBy(o: string | OrderBy | Array\u003cstring | OrderBy\u003e)\n\nSpecifies the sort order for the result set.\n\nThe ORDER BY clause is not valid in subqueries.\n\nYou also have an option to fetch only a window or page of results from the resultset using OFFSET-FETCH clause.\n\nYou may pass a string literal, an object (`{ order: 'ASC' | 'DESC', by: 'string literal' }`), or an array that contains any number of either.\n\n```JS\nquery.orderBy('column_name');\nquery.orderBy('column_name ASC');\nquery.orderBy({ by: 'column_name', order: 'ASC' });\nquery.orderBy([\n  'column_name',\n  { by: 'column2_name', order: 'DESC' }\n]);\n```\n\n### query(q: string)\n\nConvert a string into a QueryBuilder object.\n\nSometimes it's easier to start your query building process with an incomplete SQL query instead of building it from scratch.\n\n```JS\nconst query1 = new QueryBuilder().select('a').where('b = 1');\nconst query2 = new QueryBuilder().query('SELECT a WHERE b = 1');\nquery1.from('c');\nquery2.from('d');\n```\n\n### recordSet(set: number)\n\nReturns the given record set (default `0`).\n\n### recordSet(f: function)\n\nPasses the query result through the given function before returning it.\n\n### rowCount()\n\nReturns the total possible row count for a query.\n\n```JS\nconst MY_VALUE = 1;\nnew QueryBuilder()\n  .input(MY_VALUE, 'value')\n  .select('a')\n  .from('b')\n  .where('a = @value')\n  .rowCount()\n  .then(\n    (rows) =\u003e {\n      console.log(`There are ${rows} rows where a equals ${MY_VALUE}.`);\n  );\n```\n\n### select(...s: Array\u003cAliases | string\u003e)\n\nSpecifies the columns to be returned by the query.\n  \nAs strings, `query.select('column_name')` or `query.select('column1_name', 'column2_name')`.\n\nTo use aliases, pass an object where the object keys are column aliases and values are their expressions.\n\n```JS\nquery.select({\n  column: 'column',                                        // no alias\n  expression: 'MAX(column1 + column2, column3 / column4)', // alias is `expression`\n  Two: '1 + 1'\n});\n```\n\n### time()\n\nTime it took to execute the query.\n\nReturns 0 if the query has no begun executing.\n\nReturns negative if the query is still executing.\n\n```JS\n// Zero because the query has not begun to execute:\nconsole.log(query.time());\n\nquery\n  .select('a')\n  .from('b')\n  .execute()\n  .then(\n    (result) =\u003e {\n\n      // Time it took the execute:\n      console.log(query.time());\n    }\n  );\n\n// Negative, because the query is still executing asynchronously:\nconsole.log(query.time());\n```\n\n### top(n: number)\n\nSpecifies that only the first set of rows will be returned from the query result.\n\nThe set of rows can be either a number, or a percent of the rows.\n\n### where(...conditions: string[])\n\nSpecifies search conditions to restrict the rows returned.\n\n### whereIn(columnOrExpression: string, input: Input | Input[])\n\nSpecies a search condition to restrict the rows returned using an Array. To see supported Input types, check the documentation for the `input()` method.\n\n```JS\n// Select all users who are 3 or 4 feet tall.\nquery.select('username').from('users').whereIn('FLOOR(height / 12)', [ 3, 4 ]);\n\n// Select all users who are named Bob or Tim.\nquery.select('username').from('users').whereIn('name', [ 'Bob', 'Tim' ]);\n```\n\n## Sponsor 💗\n\nIf you are a fan of this project, you may\n[become a sponsor](https://github.com/sponsors/CharlesStover)\nvia GitHub's Sponsors Program.\n","funding_links":["https://github.com/sponsors/CharlesStover"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcharlesstover%2Fmssql-query-builder","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcharlesstover%2Fmssql-query-builder","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcharlesstover%2Fmssql-query-builder/lists"}