Blog

String concatenate operator on fdw_mysql tables

concatinwhere.png (64.04 KB)
 
Don't use string concatenate operator || and LIKE in WHERE clause on fdw_mysql tables in postgres
Consider you bound a foreign table having two text columns with fdw_mysql in your postgres database.
CREATE FOREIGN TABLE user(
    id integer,
    firstname text,
    name text
)
SERVER mysql_server
OPTIONS (dbname 'mysqldb', table_name 'user');

INSERT INTO user (firstname, name) VALUES
('Peter', 'Korduan'),
('Max', 'Musterman'),
('Anton', 'Kondor');

When you now query the concatenated name with || opertor LIKE and wildcard %
SELECT firstname || ' ' || name AS fullname
FROM user
WHERE firstname || ' ' || name LIKE '%Ko'
you will get no results

You have two alternatives, compare each attribute separate
SELECT firstname || ' ' || name AS fullname
FROM user
WHERE firstname LIKE '%Ko' OR name LIKE '%Ko'

or my favorit
SELECT firstname || ' ' || name AS fullname
FROM user
WHERE concat_ws(' ', firstname, name) LIKE '%Ko'

My conclusion is:
Prefere the use of concat or concat_ws before operator || at all. Especially when you want to compare with LIKE and wildcards
Side effect is that you avoid NULL results when you concatenate text with NULL
'text' || NULL => NULL vs. concat ('text', NULL) => 'text'
 Datensatz auswählen
Blog: alle auswählen
ausgewählte Datensätze:
  • als Diagramm ausgeben