Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tsql ordering data by specific string values

I have an audit table that have data for insert, update and delete operations. I am writing a report that will display data in the order of Insert, Update and Delete. I don't think the order by clause will help. any help?

like image 614
anteneh maru Avatar asked May 03 '10 13:05

anteneh maru


People also ask

How do I sort by string in SQL?

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.

How do I create a custom order in SQL?

By default SQL ORDER BY sort, the column in ascending order but when the descending order is needed ORDER BY DESC can be used. In case when we need a custom sort then we need to use a CASE statement where we have to mention the priorities to get the column sorted.

How do I sort by a specific column in 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.


1 Answers

You can use an ORDER BY combined with a CASE clause:

SELECT *
FROM auditlog
ORDER BY CASE operation_type
    WHEN 'Insert' THEN 1
    WHEN 'Update' THEN 2
    WHEN 'Delete' THEN 3
END
like image 197
Mark Byers Avatar answered Oct 28 '22 14:10

Mark Byers