Posts

Showing posts with the label sql optimization

Tuple comparison and Multi-column IN

Image
Introduction In PostgreSQL, Tuple comparison (row/tuple comparison) and Multi-column IN (IN condition on multiple columns) are two extremely powerful features that help write concise, clearer SQL queries and significantly optimize performance compared to manually chaining multiple AND/OR conditions. Tuple comparison Tuple comparison allows grouping multiple columns or values into a tuple (using parentheses (...)) and comparing these two tuples directly with each other using operators like =, <>, <, >, <=, >= Used for Keyset Pagination with more than 1 column and sorting applied Lexicographical order PostgreSQL compares elements from left to right, similar to dictionary sorting, starting by comparing the first pair of elements. If they differ, the result of the entire comparison is decided immediately without evaluating subsequent columns If they are equal, it proceeds to compare the next pair of elements, continuing this process until the end. General Example (a, ...

Using CROSS JOIN LATERAL in Postgres

Image
Introduction In standard SQL, subqueries located in the JOIN clause operate independently, they cannot see or use data from tables located before (to the left of) it. When you add the LATERAL keyword, Postgres allows the subquery on the right to directly access column values of each row in the table on the left. Differences between Join types are as follows Standard CROSS JOIN takes the Cartesian product of 2 tables independent of each other (a multiplication of 2 tables without needing a condition) CROSS JOIN LATERAL operates like a for-each loop in programming, with each row in the left table, Postgres runs the subquery on the right to perform dynamic calculations repeatedly based on values from the left table and joins the results together. INNER JOIN is the intersection between 2 datasets, it only retains rows in 2 tables when both satisfy a specific join condition, the condition in ON is mandatory (unlike CROSS JOIN which does not require passing a condition) Can be combined...