Knex.Js. Subqueries in Examples

For visual explanation of “what will happen if…” cases I will be using express.js for server-side and PostgreSQL database from previous article: Knex.Js. Beginner’s Guide in Examples

Old-fashion way

SELECT AVG(age)
FROM users;
SELECT *
FROM users
WHERE users.age > <avg-age>

Step 1:

SELECT AVG(age)
FROM users;

Step 2:

SELECT *
FROM users u
WHERE u.age > 36.75;

Easy but not effective… Let’s see on the another, more elegant approach.

Subquery-fashion way

SELECT u.first_name,
last_name,
u.age
FROM users u
WHERE u.age >
(
SELECT AVG(age)
FROM users
);

Simple, isn’t it? :)

Java, Spring, Node.js, AdonisJs, React.js and Flutter developer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store