1

I have two tables

Name  |  Age
------------
a     |   20
b     |   15


Name  | Age(varchar)
------------------
e     |  two
d     |   one

then i want to show

Name   | Age
-----------
b      |  15
a      |  20
e      |  two
d      | one

How ?

1
  • I dont see what you are trying to sort, it looks more like a union? Commented Jul 23, 2015 at 10:01

3 Answers 3

1

This can be done by union / union all operation, but the data type of Age column of these tables seems different.

so if you try to union all these tables you get an error saying;

Conversion failed when converting the varchar value 'two' to data type int

So convert the data type of age column of table 1 to varchar before union them

select id, age from (
    select id, convert(varchar(20), age) as age from tbl1
    union all
    select id, age from tbl2 
) as x
order by age

If you are OK with duplicate data use union all else union (union have additional overhead of removing duplicate data)

Note: order by age order age lexicographically

Sign up to request clarification or add additional context in comments.

Comments

0

As stated by @Matt in the comments, this does like look you wish to perform a UNION query, see msdn for an explanation on performing a UNION query.

SELECT *
FROM Table1
UNION
SELECT *
FROM Table2

Edit: if you wanted to order the results, you would then just add the ORDER BY keyword into the query.

SELECT *
FROM Table1
UNION
SELECT *
FROM Table2
ORDER BY Name

Comments

0
SELECT *
FROM Table1
UNION
SELECT *
FROM Table2
ORDER BY Name, Age;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.