Search code examples
sqlpostgresqlcomparerecord

Compare records of 2 tables with SQL


I have 2 tables with the following structure:

1-Items Table

create table if not exists items
(
    id bigserial not null primary key,
    group_id integer not null,
    description text not null,
    quantity double precision not null,
    measurement_id integer not null,
    model varchar(255),
    unitary double precision not null,
    price double precision not null,
    currency_id integer not null
);

1-Hireds Table

create table if not exists hireds
(
    id bigserial not null primary key,
    item_id integer not null constraint hireds_item_id_foreign references items on delete cascade,
    quantity double precision not null,
    price double precision not null
);

I would like to get all the items in the second table that their quantity exceeds what is already defined in the first .. for example ..

Table 1

id | name   | quantity
---------------------
1  | Item 1 | 10
2  | Item 2 | 20
3  | Item 3 | 30
4  | Item 4 | 15
5  | Item 5 | 30

Table 2

id | item_id| quantity
---------------------
1  | 1      | 15
2  | 2      | 25
3  | 3      | 35
4  | 4      | 10
5  | 5      | 29

I need a query that returns a table similar to this:

id | item_id| quantity
---------------------
1  | 1      | 5
2  | 2      | 5
3  | 3      | 5

Solution

  • A simple JOIN will do:

    select
      i.id,
      h.item_id,
      h.quantity - u.quantity as quantity
    from items i
    join hireds h on h.item_id = i.id
    where i.quantity < h.quantity
    order by i.id