Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UNION type mismatch

Tags:

postgresql

When I run below query I am getting this error

UNION types text and bigint cannot be matched

SELECT 
    1 AS STEP
  , '' AS ProviderName
  , '' AS Procedurecode
  , Claimid
  , Patient_First_Name
  , Patient_Last_Name
  , DOS
  , SUM(COALESCE(Total_Charge,0))
  , SUM(COALESCE(PaidAmount,0))
  , PostedDate
  , CheckEFTDate
  , CheckEFTNo 
FROM table_name
GROUP BY ProviderName, Claimid, Patient_First_Name, Patient_Last_Name, DOS, PostedDate,
         CheckEFTDate, CheckEFTNo
UNION ALL
SELECT 
    2 AS STEP
  , '' AS ProviderName
  , '' AS Procedurecode
  , COUNT(Claimid)
  , '' AS Patient_First_Name
  , '' AS Patient_Last_Name
  , NULL::date AS DOS
  , SUM(COALESCE(Total_Charge,0))
  , SUM(COALESCE(PaidAmount,0))
  , NULL::date AS PostedDate
  , NULL::date AS CheckEFTDate
  , '' AS CheckEFTNo 
FROM table_name
GROUP BY Claimid
like image 319
user4287146 Avatar asked Jul 20 '15 15:07

user4287146


People also ask

What does it mean type mismatch?

This error indicates that Access cannot match an input value to the data type it expects for the value. For example, if you give Access a text string when it is expecting a number, you receive a data type mismatch error.

How do you use unions with different data types?

A union is a special data type available in C that allows to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple-purpose.

Does Union require same data type?

UNION or UNION ALL have the same basic requirements of the data being combined: There must be the same number of columns retrieved in each SELECT statement to be combined. The columns retrieved must be in the same order in each SELECT statement. The columns retrieved must be of similar data types.

Can column have different data types in Union?

The columns of joining tables may be different in JOIN but in UNION the number of columns and order of columns of all queries must be same.


1 Answers

My mistake was is that in union name of columns doesnt matter, but order does matter (maybe I'm wrong, I can't find documentation)

Example:

1) This is fine

select
1 :: integer as someint, 
'1' :: text as sometext

union

select
2 :: integer as someint,
'2' :: text as sometext

returns

someint sometext
1   1   1
2   2   2

2) this is not fine

select
1 :: integer as someint, 
'1' :: text as sometext

union

select
'2' :: text as sometext,
2 :: integer as someint

throws

Error(s), warning(s):

42804: UNION types integer and text cannot be matched

try yourself https://rextester.com/l/postgresql_online_compiler

like image 91
srghma Avatar answered Sep 21 '22 23:09

srghma