Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rmorenobello/b0dec54abc3a8098c77d4236b5879a93 to your computer and use it in GitHub Desktop.
Save rmorenobello/b0dec54abc3a8098c77d4236b5879a93 to your computer and use it in GitHub Desktop.
Don't Use the String Concatenation Trick in SQL Predicates
-- NOTA: no recuerdo por qué todo esto en lugar de un simple join ?!?!?!
-- DO NOT DO THIS!!!
CREATE INDEX idx_customer_name ON customer (last_name, first_name);
SELECT *
FROM customer
WHERE first_name || last_name IN (
SELECT first_name || last_name
FROM actor
)
/*
Is slow and can bring false matches:
-- What we expected
first_name || last_name = 'JENNIFER' || 'DAVIS'
-- What we got
first_name || last_name = 'JENNI' || 'FERDAVIS'
*/
-- Using an "impossible" separator is very slow (final hash join with full actor index):
CREATE INDEX idx_actor_name ON actor (last_name, first_name);
SELECT *
FROM customer
WHERE address_id = 10
AND first_name || '������' || last_name IN (
SELECT first_name || '������' || last_name
FROM actor
)
-- END of DO NOT DO THIS
-- ==========> DO THIS <===========
-- with ORACLE, PostgreSQL, ... "row constructors":
SELECT *
FROM customer
WHERE address_id = 10
AND (first_name, last_name) IN (
SELECT first_name, last_name
FROM actor
);
-- or with exists
SELECT *
FROM customer c
WHERE address_id = 10
AND EXISTS (
SELECT 1
FROM actor a
WHERE c.first_name = a.first_name
AND c.last_name = a.last_name
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment