Alias a table in Knex Alias a table in Knex sql sql

Alias a table in Knex


I think I figured it out. In knex.js, say you specify a table like:

knex.select( '*' ).from( 'Users' )

Then you can just add the AS keyword within the quotes of the table name to alias it, like so:

knex.select( '*' ).from( 'Users AS u' )

..and you can do this for column names, too; so my original SQL would look like this in knex-land:

    knex.select( 'w.*', 'ua.name AS ua_name', 'uw.name AS uw_name' )    .innerJoin( 'Users AS ua', 'author_id', 'ua.id' )    .leftJoin( 'Users as uw', 'winner_id', 'uw.id' )

I guess I got confused by the presence of knex's .as() method, which (as far as I currently understand) is meant just for subqueries, not for aliasing tables or column names.


There are two ways to declare an alias for identifier (table or column). One can directly give as aliasName suffix for the identifier (e.g. identifierName as aliasName) or one can pass an object { aliasName: 'identifierName' }.

So, the following code:

 knex.select('w.*', 'ua.name', 'uw.name')  .from({ w: 'Words' })  .innerJoin({ ua: 'Users' }, 'w.author_id', '=', 'ua.id')  .leftJoin({ uw: 'Users' }, 'w.winner_id', '=', 'uw.id')  .toString()

will compile to:

select "w".*, "ua"."name", "uw"."name"from "Words" as "w"inner join "Users" as "ua" on "w"."author_id" = "ua"."id"left join "Users" as "uw" on "w"."winner_id" = "uw"."id"


Found this question when tried to figure out how to select all columns from all joined tables without overriding one another if column names are equals. This is how I did it, prepending each with its "tablename_":

const columnToText = (table, column) => `${table}.${column} as ${table}_${column}`;const prepareColumns = async (table) => {  const columnsInfo = await knex(table).columnInfo();  return Object.keys(columnsInfo).map(column => columnToText(table, column));};const selectColumns = (await Promise.all([  'joined_table1',  'joined_table2',  'main_table',].map(prepareColumns)))  .reduce((acc, item) => ([...acc, ...item]), []);const data = await knex('main_table')  .leftJoin('joined_table1', 'main_table.joined_table1_id', 'joined_table1.id')  .leftJoin('joined_table2', 'main_table.joined_table1_id', 'joined_table2.id')  .select(...selectColumns);