user2961127 user2961127 - 4 months ago 9
MySQL Question

Formatting the output using select statement

I have two select statements which are as mentioned below

SELECT 'MY OUTPUT'
SELECT * FROM MY TABLE


ON Execution 'MY OUTPUT' is printed first and then there is a gap for next select.
I want to use something like 'UNION' to combine two statements.
I am using :

SELECT 'MY OUTPUT' UNION
SELECT * FROM MY TABLE


But, I am getting error:
All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.

Answer

So here's what's happening:

The error you're getting (All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.) is because there are more columns in one select than the other.

You could use the same blank columns in your first query as there are in [My Table] which would make your query look like:

SELECT 'MY OUTPUT' , '', '' ,'', '' --(no. of columns should match those in MY TABLE)
UNION
SELECT * FROM [MY TABLE]

I'm guessing you want an excel style cell merge which is not possible as the output of a select query unfortunately.