/    Sign up×
Community /Pin to ProfileBookmark

MySQL Order By specific string then alphabetically

Is it possible to order by a specific string then alphabetically?

For example, I want to show all the SMITHS first then ‘ORDER BY `userName` DESC ‘

I don’t believe it is, but I welcome any ideas.

to post a comment
PHP

3 Comments(s)

Copy linkTweet thisAlerts:
@NogDogOct 15.2021 — Only way that pops to mind is to add an additional case column to the select:
[code=sql]
select
*, -- or list specific columns you want
case
when last_name = 'SMITH' then 0 -- adjust upper-/lower-case as needed
else 1
end as name_sort
from the_table
order by name_sort, last_name, first_name
[/code]
Copy linkTweet thisAlerts:
@boohooOct 15.2021 — @NogDog#1638196 you don't need this complexity. SQL returns boolean expressions as 1 or 0, so this is enough:

``sql<i>
</i>SELECT *
FROM the_table
ORDER BY last_name = 'SMITH' DESC,
last_name,
first_name<i>
</i>
`</CODE>
<CODE>
``
Copy linkTweet thisAlerts:
@NogDogOct 15.2021 — @boohoo#1638202 Cool, just tried (something like) it in PostgreSQL to confirm it supports that sort of thing, too:
[code=sql]
select predicate_type_id
from some_schema.predicate_type
order by mod(predicate_type_id, 2), predicate_type_id
[/code]

[code=text]
OUTPUT:
4
6
8
10
12
14
16
1
7
9
11
13
15
17
[/code]
×

Success!

Help @kiwis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.25,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...