Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order by an arbitrary condition in SQL

I have the following table:

CREATE TABLE Bable
    (
     id int identity primary key, 
     name varchar(20), 
     about varchar(30)
    );
INSERT INTO Bable (name,about) VALUES
('ООО Name Firm 1','texttexttexttext'),
('ООО Name Firm 2','texttexttexttext'),
('ООО Name Firm 3','texttexttexttext'),
('ООО Name Firm 4','texttexttexttext'),
('ООО Name Firm 5','texttexttexttext'),
('ООО Name Firm $1','texttexttexttext'),
('ООО Name Firm $2','texttexttexttext'),
('ООО Name Firm $3','texttexttexttext'),
('ООО Name Firm 6','texttexttexttext'),
('ООО Name Firm 7','texttexttexttext')

And I can write a query like the following:

SELECT * FROM Bable WHERE about = 'texttexttexttext'

How can I alter this query to return results ordered such that those with names containing "$" appear first, followed by those that do not, with each group then ordered by name ascending?

Structure of the table is here

like image 856
Leo Loki Avatar asked Mar 22 '13 05:03

Leo Loki


People also ask

How do I order a to z in SQL?

The SQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

Can you ORDER BY a function SQL?

The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.


2 Answers

SELECT *
FROM   Bable
ORDER  BY CASE WHEN name LIKE '%$..' THEN 0 ELSE 1 END,
          Name 
  • SQLFiddle Demo
like image 188
John Woo Avatar answered Oct 05 '22 07:10

John Woo



select * from Bable 
order by charindex('$',name,0) desc, name asc
SQL Fiddle Demo
like image 34
ljh Avatar answered Oct 05 '22 06:10

ljh