Knex.Js. Subqueries in Examples

Image for post
Image for post

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

What if we need to fetch users that have age more that average age of all users?

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

Step 1:

SQL Example:

SELECT AVG(age)
FROM users;
Image for post
Image for post
Image for post
Image for post

Step 2:

SQL Example:

SELECT *
FROM users u
WHERE u.age > 36.75;
Image for post
Image for post
Image for post
Image for post

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

Subquery-fashion way

The simplest (I think) example of a subquery solution of a previous task will look like this:

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

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