Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using different order by with union

I want to write a query like

    select top 10 * from A
    order by price
    union
    select top 3 * from A 
    order by price

or sth like that

    select top 10 * from A
    where name like '%smt%'
    order by price
    union
    select top 3 * from A
    where name not like '%smt%'
    order by price 

Can you please help me?

like image 951
Barny Avatar asked Nov 19 '12 13:11

Barny


People also ask

Can you use ORDER BY with UNION?

Union is a type of operator in MySQL. We can use ORDER BY with this to filter records. Use UNION if you want to select rows one after the other from several tables or several sets of rows from a single table all as a single result set. Let us see an example.

Why does ORDER BY not work with UNION?

From MySQL documentation: ... use of ORDER BY for individual SELECT statements implies nothing about the order in which the rows appear in the final result because UNION by default produces an unordered set of rows. Basically the only time an ORDER in a union will be useful is if you are using LIMIT as well.

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.

How do you use unions with different number of columns?

Basic rules for combining two or more queries using UNIONnumber of columns and order of columns of all queries must be same. 2.) the data types of the columns on involving table in each query must be same or compatible.


1 Answers

This should work:

SELECT * 
FROM (SELECT TOP 10 A.*, 0 AS Ordinal
      FROM A
      ORDER BY [Price]) AS A1

UNION ALL

SELECT * 
FROM (SELECT TOP 3 A.*, 1 AS Ordinal
      FROM A
      ORDER BY [Name]) AS A2

ORDER BY Ordinal

From MSDN:

In a query that uses UNION, EXCEPT, or INTERSECT operators, ORDER BY is allowed only at the end of the statement. This restriction applies only to when you specify UNION, EXCEPT and INTERSECT in a top-level query and not in a subquery.

Edited: to force the order you need to apply an ORDER BY to the outer query. I've added a constant value column to both queries.

like image 65
Tim Schmelter Avatar answered Sep 21 '22 17:09

Tim Schmelter