Skip to main content

Command Palette

Search for a command to run...

Deno Mysql - Query VS Execute

What's the difference between them?

Updated
1 min read

When you look at the Deno Mysql documentation you can use two functions to run your query :

client.execute(/*SQL*/)
client.query(/*SQL*/)

I wasn't sure when to use what, so I consulted the code to find out.

Both function work the same as the query function is internally using the execute function. But they have not the same return value:

  • The execute function return an ExecuteResult object.

  • While the query function return either an ExecuteResult object or an array.

Basicaly it's means that query is more interesting if you want to retrieve the content of the "rows" directly (wich is mostly the case on a SELECT query)

export type ExecuteResult = {
  affectedRows?: number;
  lastInsertId?: number;
  fields?: FieldInfo[];
  rows?: any[];
  iterator?: any;
};

async query(sql: string, params?: any[]): Promise<ExecuteResult | any[]> {
    const result = await this.execute(sql, params);
    if (result && result.rows) {
      return result.rows;
    } else {
      return result;
    }
  }

When to use them?

For HTTP calls:

  • Use query for GET endpoint

  • Use execute for POST/PUT/UPDATE/DELETE endpoint

In terms of SQL:

  • Use query on SELECT statements or any other SQL operation that returns rows from the database.

  • Use execute on INSERT, UPDATE, DELETE, or any other SQL operation that modifies data in the database

What I've learned today

Part 4 of 5

This serie gather all the new things I learn on a day to day basis that can be usefull for everyone. It can be about anything, tech, books, people, hack, etc.

Up next

Mongoose - Add a unique index on an existing collection

The "sparse" option