I have a query in which I use UNION to join two similar queries into one, in the results I would like the result of the first query to come before the results of the second query, however UNION by default brings the mixed results. This is my original query:
SELECT users.name, users.last_name
FROM users
WHERE users.name LIKE 'Paulo%'
UNION
SELECT users.name, users.last_name
FROM users
WHERE users.name LIKE '%Paulo%';
Resultado:
name | last_name
-------------+-----------
João Paulo | Silva ----> Second subquery
Paulo | Roberto ----> First subquery
Pedro Paulo | Camargo ----> Second subquery
A possible solution that I found was to add an attribute in the subquery where I inform the position of the object, however this interfered with the UNION grouping causing the results to be duplicated
SELECT 1 as position, users.name, users.last_name
FROM users
WHERE users.name LIKE 'Paulo%'
UNION
SELECT 2 as position, users.name, users.last_name
FROM users
WHERE users.name LIKE '%Paulo%'
ORDER BY position;
Result:
position | name | last_name
----------+-------------+-----------
1 | Paulo | Roberto
2 | João Paulo | Silva
2 | Paulo | Roberto (Duplicate record)
2 | Pedro Paulo | Camargo
Now I am in need of a solution to ignore duplicate records of the final result