What is the difference between LATERAL and a subquery in PostgreSQL?

后端 未结 4 1084
花落未央
花落未央 2020-11-21 08:58

Since Postgres came out with the ability to do LATERAL joins, I\'ve been reading up on it, since I currently do complex data dumps for my team with lots of inef

4条回答
  •  攒了一身酷
    2020-11-21 09:21

    One thing no one has pointed out is that you can use LATERAL queries to apply a user-defined function on every selected row.

    For instance:

    CREATE OR REPLACE FUNCTION delete_company(companyId varchar(255))
    RETURNS void AS $$
        BEGIN
            DELETE FROM company_settings WHERE "company_id"=company_id;
            DELETE FROM users WHERE "company_id"=companyId;
            DELETE FROM companies WHERE id=companyId;
        END; 
    $$ LANGUAGE plpgsql;
    
    SELECT * FROM (
        SELECT id, name, created_at FROM companies WHERE created_at < '2018-01-01'
    ) c, LATERAL delete_company(c.id);
    

    That's the only way I know how to do this sort of thing in PostgreSQL.

提交回复
热议问题