4

Let's say I have such SQL query which I make to PostgreSQL database. As you can see I'm repeating the same subquery just to get another column. I am convinced that this is ineffective. What is the best way to execute an sql query for your opinion?

SELECT
    TABLE_A.COLUMN_1,
    TABLE_A.COLUMN_2,
    (
        SELECT
            TABLE_B.COLUMN_A,
        FROM 
            TABLE_B
        WHERE 
            TABLE_B.COLUMN_Z ILIKE CONCAT('%', TABLE_A.COLUMN_2, '%')
    ) AS COLUMN_3,
    (
        SELECT
            TABLE_B.COLUMN_B,
        FROM 
            TABLE_B
        WHERE 
            TABLE_B.COLUMN_Z ILIKE CONCAT('%', TABLE_A.COLUMN_2, '%')
    ) AS COLUMN_4,
FROM
    TABLE_A
0

2 Answers 2

7

Use a lateral join:

SELECT a.COLUMN_1, a.COLUMN_2, b.*
FROM TABLE_A a LEFT JOIN LATERAL
     (SELECT b.COLUMN_A, b.COLUMN_B
      FROM TABLE_B b
      WHERE b.COLUMN_Z ILIKE CONCAT('%', a.COLUMN_2, '%')
    ) b
    ON 1=1;
Sign up to request clarification or add additional context in comments.

Comments

1

Use join

SELECT
    TABLE_A.COLUMN_1,
    TABLE_A.COLUMN_2, TABLE_B.COLUMN_A AS COLUMN_3, ABLE_B.COLUMN_B AS COLUMN_4
FROM
    TABLE_A 
JOIN
    TABLE_B ON TABLE_B.COLUMN_Z LIKE CONCAT('%', TABLE_A.COLUMN_2, '%')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.