Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a row at the end of SQL Select using UNION

Tags:

sql

oracle

I created a view in a record using some filters and i have to add lines that contains just ids from another table and a specific row at the end of the sql result.

So the expected result is something like that:

    Column 1 | Column 2 | Column 3 | Column4
1   0001     | 565      | AM1      | DR01
.
.
59  TEST1    |          |          |
60  NON_IMMO |          |          |

Line 59 is the id from the second table and line 60 is the specifix row. My query is like that :

SELECT DISTINCT a.asset_id 
 , a.serial_id 
 , a.VIN 
 , b.project_id 
  FROM ps_asset a 
 WHERE --Some conditions  
  UNION 
 SELECT PO_GROUP_ID 
 ,' ' 
 , ' ' 
 , ' ' 
  FROM PS_PO_GROUP_TBL 
  UNION 
 SELECT 'NON_IMMO' 
 ,' ' 
 ,' ' 
 ,' ' 
  FROM dual

But the problem is using this I don't get the specific row at the end.

I feel like the SGBD show the 2 UNIONS ordered by alphabet.

    Column 1 | Column 2 | Column 3 | Column4
1   0001     | 565      | AM1      | DR01
.
.
59  NON_IMMO |          |          |
60  TEST1    |          |          |

Thanks for help.

like image 221
kh.tab Avatar asked Dec 29 '17 15:12

kh.tab


People also ask

How do I add a row to a SELECT query?

To insert a row into a table, you need to specify three things: First, the table, which you want to insert a new row, in the INSERT INTO clause. Second, a comma-separated list of columns in the table surrounded by parentheses. Third, a comma-separated list of values surrounded by parentheses in the VALUES clause.

How do you append a row in SQL?

Here is the basic syntax for adding rows to a table in SQL: INSERT INTO table_name (column1, column2, column3,etc) VALUES (value1, value2, value3, etc); The first line of code uses the INSERT statement followed by the name of the table you want to add the data to.


1 Answers

Change the last UNION to a UNION ALL to skip elimination of duplicates (which as a side effect orders the lines). That should be enough...

...
FROM PS_PO_GROUP_TBL 
UNION ALL
SELECT 'NON_IMMO' 
...
like image 161
Per Huss Avatar answered Sep 28 '22 18:09

Per Huss