Today I Learned

hashrocket A Hashrocket project

Combine Records from Different Tables

Let's say you have 2 users and 3 categories and you want a query to return the combination of all the records, resulting in 6 rows.

You can use cross join to do that:

select
  users.id as user_id,
  categories.id as category_id
from users cross join categories


 user_id | category_id
---------+-------------
       1 |           1
       1 |           2
       1 |           3
       2 |           1
       2 |           2
       2 |           3
See More #sql TILs
Looking for help? Hashrocket developers believe that data quality is as important as code quality. We enjoy all the challenges of relational databases, from finding the fastest index, to structuring data to fit the needs of an application. We're eager to share our experiences; check out PG Casts, our series of free PostgreSQL screencasts.