Skip to content

MARS Engine — Query Builder Examples

This document contains practical examples of using the MARS Engine query builder to perform common database operations.

Select Query

js
const users = db.select("*")
  .from("users")
  .where("usr_name", "Tom")
  .exec();

Insert Query (with .set())

js
db.insert("users")
  .set("usr_name", "Alice")
  .set("usr_email", "alice@example.com")
  .exec();

Update Query (with .set())

js
db.update("users")
  .set("usr_email", "alice@newdomain.com")
  .where("usr_id", 42)
  .exec();

Delete Query

js
db.delete("users")
  .where("usr_id", 42)
  .exec();

Join with Conditions

js
const data = db.select("u.usr_name", "p.post_title")
  .from("users as u")
  .innerJoin("posts as p", "p.usr_id", "u.usr_id")
  .where("u.active", true)
  .exec();

Complex Conditions with orWhere

js
const result = db.select("*")
  .from("products")
  .where("category", "books")
  .orWhere("category", "magazines")
  .exec();

Reusable Conditional Logic with .condition()

You can generate custom conditions with the 'condition()' function. It uses parameters in the same way as 'where()' function.

js
let queryBuilder = db.select("*").from("table_1");
let myCondition = db.condition('table1.col_1 = "John Doe"');
// and 
myCondition.and('table_2.col_2', 'NOT IN', [1, 2, 3]);
// or
myCondition.or('table_2.col_4', 'Col4Val');

queryBuilder.innerJoin('table_2', 'table_2.col_1 = table_1.col_1');
queryBuilder.where(myCondition);

Generated SQL:

sql
SELECT  * FROM table_1 INNER JOIN table_2 ON  table_2.col_1 = table_1.col_1
WHERE ( table1.col_1 = "John Doe" ) 
  AND ( `table_2`.`col_2` NOT IN ( 1, 2, 3 ) ) 
  OR ( `table_2`.`col_4` = 'Col4Val' )

Preview SQL without Execution

js
const sql = db.select("*")
  .from("users")
  .where("usr_id", 5)
  .toSql();

write("sql",sql); // SELECT * FROM users WHERE usr_id = 5