MySQL match pattern and select number and letters - mysql

I have a list of IDs which are created in various third party applications systems and manually added to our system. I need to try and auto increment these IDs based on the largest number. The values are either entirely a number or any number of letters followed by any number of numbers.
For example:
Array ( [works_id] => MD001 [num] => 0 )
Array ( [works_id] => WX9834V [num] => 0 )
Array ( [works_id] => WK009 [num] => 0 )
Array ( [works_id] => W4KHA2 [num] => 0 )
Array ( [works_id] => MD001 [num] => 0 )
Array ( [works_id] => DE1234 [num] => 0 )
Array ( [works_id] => 99 [num] => 99 )
Array ( [works_id] => 100 [num] => 100 )
In the above example, I would need to return 'DE' and 1234 as 1234 is the largest number which matches the pattern (WX9834V does not match as it is LLNNNNL)
So far I have tried:
SELECT works_id, CAST(works_id as UNSIGNED) as num
FROM table
WHERE (works_id REGEXP '^[a-zA-Z]+[0-9]' or works_id REGEXP '^[0-9]+$')
But this returns all rows and returns 0 for the number part unless it is only made up of numbers - how can I return only 'DE' and 1234 from the above?

From the comments, I understant that your primary intent is to select the records that do match your format spec (possibly characters at the beginning of the string, then mandatory numbers until the end of string).
The problem with you current query is that the first regexp, '^[a-zA-Z]+[0-9]' is too permissive: it does allow non-numbers characters at the end of the field, and would be better written '^[a-zA-Z]+[0-9]+$'
Bottom line, the two regexes can be combined into one:
SELECT works_id
FROM mytable
WHERE works_id REGEXP '^[a-zA-Z]*[0-9]+$'
The regexp means:
^ beginning of the string
[a-zA-Z]* 0 to N letters
[0-9]+ at least one digit
$ end of string
In this db fiddle with your test data, this returns:
| works_id |
| -------- |
| MD001 |
| WK009 |
| MD001 |
| 99 |
| 100 |
NB : in MySQL pre-8.0, splitting the string in order to find the max numerical pain is hard to do, since functions such as REGEXP_REPLACE are not available. It is probably easier to do this in your application (unless you have a very large numbers of matching records...). You can have a look at this post or this other one for solutions that mostly rely on MySQL functions.

Related

Apostrophe at beginning/end of search string not treated as part of a word by RegEx

We run a dictionary and have run into a problem with searches that contain an apostrophe at the start of a search string. In English words like 'twas are quite rare but in the language we're dealing with, ' is considered a word character and extremely common at the start of a phrase (for instance 's) and also at the end of words (for instance a').
Oddly enough, RegEx searches don't seem to struggle with this if it's in the middle (for example air a' bhòrd gets all the desired results) but ' at beginning or end of a search string is not treated as part of a word by RegEx.
We've ascertained this is part of the RegEx specification (only alphanumeric characters and _ are treated as part of a word) but we're wondering if it is it possible to write a RegEx expression that also treats apostrophes as part of a word?
This is what we're currently getting:
-- Demonstration on MySQL 5.6.21 Community
Select ('cat''s' REGEXP CONCAT('[[:<:]]', 'cat''s', '[[:>:]]'));
-- returns 1
Select ('''cat''s' REGEXP CONCAT('[[:<:]]' ,'''cat''s' ,'[[:>:]]' ));
-- returns 0
Select ('_cat''s' REGEXP CONCAT('[[:<:]]' ,'_cat''s' ,'[[:>:]]' ));
-- returns 1
Select ('-cat''s' REGEXP CONCAT('[[:<:]]' ,'-cat''s' ,'[[:>:]]' ));
-- returns 0
Select (' cat''s' REGEXP CONCAT('[[:<:]]' ,' cat''s' ,'[[:>:]]' ));
-- returns 0
Select ('cat''' REGEXP CONCAT('[[:<:]]' ,'cat''' ,'[[:>:]]' ));
-- returns 0
Any suggestions greatly welcomed :)
I think that you should provide your own definition of what a word character is, instead of relying on default ICE word boundaries ([[:<:]], [[:>:]]). From the mysql 5.6 documentation :
A word is a sequence of word characters that is not preceded by or followed by word characters. A word character is an alphanumeric character in the alnum class or an underscore (_).
That would mean : '^|[^[:alnum:]_]'
^ -- the beginning of the string
| -- OR
[^ -- any character OTHER than
[:alnum:] -- an alphanumeric character
_ -- an underscore
]
And ICE end of string would be : '[^[:alnum:]_]|$', where $ represents the end of string.
You could just modify this to add the single quote in the character class, like :
beginning : '^|[^[:alnum:]_'']'
end : '[^[:alnum:]_'']|$'
Here is your regex :
SELECT (val REGEXP CONCAT('(^|[^[:alnum:]_''])', 'cat''s', '([^[:alnum:]_'']|$)'));
See the demo on dbfiddle
Schema (MySQL v5.6)
Query #1
Select ('cat''s'
REGEXP CONCAT('(^|[^[:alnum:]_''])', 'cat''s', '([^[:alnum:]_'']|$)')) res;
| res |
| --- |
| 1 |
Query #2
Select ('''cat''s'
REGEXP CONCAT('(^|[^[:alnum:]_''])', '''cat''s', '([^[:alnum:]_'']|$)' )) res;
| res |
| --- |
| 1 |
Query #3
Select ('_cat''s'
REGEXP CONCAT('(^|[^[:alnum:]_''])', '_cat''s' , '([^[:alnum:]_'']|$)' )) res;
| res |
| --- |
| 1 |
Query #4
Select ('-cat''s'
REGEXP CONCAT('(^|[^[:alnum:]_''])', '-cat''s' , '([^[:alnum:]_'']|$)' )) res;
| res |
| --- |
| 1 |
Query #5
Select (' cat''s'
REGEXP CONCAT('(^|[^[:alnum:]_''])', ' cat''s' , '([^[:alnum:]_'']|$)' )) res;
| res |
| --- |
| 1 |
Query #6
Select ('cat'''
REGEXP CONCAT('(^|[^[:alnum:]_''])', 'cat''' , '([^[:alnum:]_'']|$)' )) res;
| res |
| --- |
| 1 |

Rails Multiplying value of afcolumn using ActiveRecord

I want to multiply a value of an specific column considering the user id.
Assume I have a table users with user 1 (id 1) and user 2 (id 2), and a table animals which has name and mensal_cost.
Ok, then I added two animals for user 1 (id 1) and 1 animal for user 2 (id 2)
I want to know how I can using ActiveRecord calculates the mensal_cost income after 3 months increasing the same base value, it means I have to multiply the actual value by 3.
I'm trying something like this:
Animal.where(user_id: ?).sum('3*mensal_cost')
Since I don't know how many users can exist, I must write a call which will list for each user id the amount after 3 months.
Ok, you nearly had it on your own - just the minor details can be like this:
user_ids = [id1, id2]
full_sum = 3 * Animal.where(:user_id => user_ids).sum(:mensal_cost)
Note: don't forget you can multiply by three after summing and it'll be the same as summing each one multiplied by 3 eg
(3 * 2) + (3 * 3) + (3 * 4) == 3 * (2 + 3 + 4)
or you can iterate through the users to get their individual sums like so:
mensal_sums = {}
user_ids = [id1, id2]
user_ids.each do |user_id|
mensal_sums[user_id] = 3 * Animal.where(:user_id => user_id).sum(:mensal_cost)
end
puts mensal_sums
=> {id1 => 63, id2 => 27}
EDIT
and one where you want the user name as well:
mensal_sums = {}
users = User.find([id1, id2])
users.each do |user|
mensal_sums[user.id] = {:user_name => user.name,
:sum => (3 * user.animals.sum(:mensal_cost)) }
end
puts mensal_sums
=> {id1 => {:user_name => "Bob Jones", :sum => 63},
id2 => {:user_name => "cJane Brown", :sum =>27}
}
I just figured out the solution:
Animal.group('user_id').sum('3*mensal_cost')
the group was the key :D

Mysql Input/Output query

I have two querys:
SELECT LancamentoEntrada.*,
TipoEntrada.descricao AS nome,
Usuario.nome AS obreiro
FROM lancamento_entradas LancamentoEntrada,
tipo_entradas TipoEntrada,
obreiros Obreiro,
usuarios Usuario
WHERE LancamentoEntrada.tipo_entrada_id = TipoEntrada.id
AND TipoEntrada.somar_caixa = 1
AND LancamentoEntrada.obreiro_id = Obreiro.id
AND Usuario.id = Obreiro.usuario_id
AND LancamentoEntrada.data_entrada >= '{$begin}'
AND LancamentoEntrada.data_entrada <= '{$end}'
ORDER BY LancamentoEntrada.data_entrada
And
SELECT LancamentoSaida.*,
TipoSaida.descricao AS nome
FROM lancamento_saidas LancamentoSaida,
tipo_saidas TipoSaida
WHERE LancamentoSaida.tipo_saida_id = TipoSaida.id
AND TipoSaida.somar_caixa = 1
AND LancamentoSaida.data_saida >= '{$begin}'
AND LancamentoSaida.data_saida <= '{$end}'
ORDER BY LancamentoSaida.data_saida
Which generate the follow arrays:
// Query 1
Array(
[0] => Array (
[id] => 3
[tipo_entrada_id] => 1
[data_entrada] => 2012-05-08
[data_vencimento] => 2012-05-08
[obreiro_id] => 2
[valor_pago] => 20.00
[valor_pagar] => 0.01
[observacoes] => TESTE
)
[1] => Array (
[...]
)
)
// Query 2
Array (
[0] => Array (
[id] => 1
[tipo_saida_id] => 1
[data_saida] => 2012-05-08
[data_vencimento] => 2012-05-08
[valor_pago] => 200.00
[observacoes] => tESTE
)
[1] => Array (
[...]
)
)
But, I want to do one query, listing inputs and outputs, how I can acomplish this?
If need more explanation, please, ask-me.
EDIT 1
inputs are generated from first query, output from second.
EDIT 2
The querys need to generate report of financial input/output, so, the first query get all input stored and the second get all output generated, both betwenn from one period. I need to generate a list with all, input and output, ordered by date.
Edit 3
I have done this query, the problem is, how I know when is input and when is output?
Tried ISNULL and CASEs, but not work.
(SELECT LancamentoEntrada.data_entrada AS data,
LancamentoEntrada.data_vencimento AS vencimento,
LancamentoEntrada.valor_pago AS valor,
LancamentoEntrada.observacoes AS observacoes,
TipoEntrada.descricao AS nome
FROM lancamento_entradas LancamentoEntrada,
tipo_entradas TipoEntrada
WHERE LancamentoEntrada.tipo_entrada_id = TipoEntrada.id
AND TipoEntrada.somar_caixa = 1
)
UNION
(SELECT LancamentoSaida.data_saida AS data,
LancamentoSaida.data_vencimento AS vencimento,
LancamentoSaida.valor_pago AS valor,
LancamentoSaida.observacoes AS observacoes,
TipoSaida.descricao AS nome
FROM lancamento_saidas LancamentoSaida,
tipo_saidas TipoSaida
WHERE LancamentoSaida.tipo_saida_id = TipoSaida.id
AND TipoSaida.somar_caixa = 1
)
If the only thing you still need is to identify which records came from which query you just need to add a literal to each query.
( SELECT
'Input' as rec_type,
LancamentoEntrada.data_entrada AS data,
LancamentoEntrada.data_vencimento AS vencimento,
LancamentoEntrada.valor_pago AS valor,
LancamentoEntrada.observacoes AS observacoes,
TipoEntrada.descricao AS nome
FROM lancamento_entradas LancamentoEntrada,
tipo_entradas TipoEntrada
WHERE LancamentoEntrada.tipo_entrada_id = TipoEntrada.id
AND TipoEntrada.somar_caixa = 1
)
UNION ALL
(SELECT
'Output' as rec_type,
LancamentoSaida.data_saida AS data,
LancamentoSaida.data_vencimento AS vencimento,
LancamentoSaida.valor_pago AS valor,
LancamentoSaida.observacoes AS observacoes,
TipoSaida.descricao AS nome
FROM lancamento_saidas LancamentoSaida,
tipo_saidas TipoSaida
WHERE LancamentoSaida.tipo_saida_id = TipoSaida.id
AND TipoSaida.somar_caixa = 1
)
As an aside you'll get better performance if you UNION ALL Since UNION would remove duplicates from the two sets which you won't have in this case.

ActiveRecord joins and where

I have three models Company, Deal and Slot. They are associated as Company has_many deals and Deal has_many slots. All the A company can be expired if all of its deals are expired. And a deal is expired when all of its slots are expired.
I have written a scope..
scope :expired,
lambda { |within|
self.select(
'DISTINCT companies.*'
).latest(within).joins(
:user =>{ :deals => :slots }
).where(
"companies.spam = false AND deals.deleted_at IS NULL
AND deals.spam = false AND slots.state = 1
OR slots.begin_at <= :time",
:time => Time.zone.now + SLOT_EXPIRY_MARGIN.minutes
)
}
The above scope does not seem right to me from what I am trying to achieve. I need companies with all of its slots for all the deals are either in state 1 or the begin_at is less than :time making it expired.
Thanks for having a look in advance.
AND has a higher precedence than OR in SQL so your where actually gets parsed like this:
(
companies.spam = false
and deals.deleted_at is null
and deals.spam = false
and slots.state = 1
)
or slots.begin_at <= :time
For example (trimmed a bit for brevity):
mysql> select 1 = 2 and 3 = 4 or 5 = 5;
+---+
| 1 |
+---+
mysql> select (1 = 2 and 3 = 4) or 5 = 5;
+---+
| 1 |
+---+
mysql> select 1 = 2 and (3 = 4 or 5 = 5);
+---+
| 0 |
+---+
Also, you might want to use a placeholder instead of the literal false in the SQL, that should make things easier if you want to switch databases (but of course, database portability is largely a myth so that's just a suggestion); you could also just use not in the SQL. Furthermore, using a class method is the preferred way to accept arguments for scopes. Using scoped instead of self is also a good idea in case other scopes are already in play but if you use a class method, you don't have to care.
If we fix the grouping in your SQL with some parentheses, use a placeholder for false, and switch to a class method:
def self.expired(within)
select('distinct companies.*').
latest(within).
joins(:user => { :deals => :slots }).
where(%q{
not companies.spam
and not deals.spam
and deals.deleted_at is null
and (slots.state = 1 or slots.begin_at <= :time)
}, :time => Time.zone.now + SLOT_EXPIRY_MARGIN.minutes)
end
You could also write it like this if you prefer little blobs of SQL rather than one big one:
def self.expired(within)
select('distinct companies.*').
latest(within).
joins(:user => { :deals => :slots }).
where('not companies.spam').
where('not deals.spam').
where('deals.deleted_at is null').
where('slots.state = 1 or slots.begin_at <= :time', :time => Time.zone.now + SLOT_EXPIRY_MARGIN.minutes)
end
This one also neatly sidesteps your "missing parentheses" problem.
UPDATE: Based on the discussion in the comments, I think you're after something like this:
def self.expired(within)
select('distinct companies.*').
latest(within).
joins(:user => :deals).
where('not companies.spam').
where('not deals.spam').
where('deals.deleted_at is null').
where(%q{
companies.id not in (
select company_id
from slots
where state = 1
and begin_at <= :time
group by company_id
having count(*) >= 10
)
}, :time => Time.zone.now + SLOT_EXPIRY_MARGIN.minutes
end
That bit of nastiness at the bottom grabs all the company IDs that have ten or more expired or used slots and then companies.id not in (...) excludes them from the final result set.

MySQL 'Order By' - sorting alphanumeric correctly

I want to sort the following data items in the order they are presented below (numbers 1-12):
1
2
3
4
5
6
7
8
9
10
11
12
However, my query - using order by xxxxx asc sorts by the first digit above all else:
1
10
11
12
2
3
4
5
6
7
8
9
Any tricks to make it sort more properly?
Further, in the interest of full disclosure, this could be a mix of letters and numbers (although right now it is not), e.g.:
A1
534G
G46A
100B
100A
100JE
etc....
Thanks!
update: people asking for query
select * from table order by name asc
People use different tricks to do this. I Googled and find out some results each follow different tricks. Have a look at them:
Alpha Numeric Sorting in MySQL
Natural Sorting in MySQL
Sorting of numeric values mixed with alphanumeric values
mySQL natural sort
Natural Sort in MySQL
Edit:
I have just added the code of each link for future visitors.
Alpha Numeric Sorting in MySQL
Given input
1A 1a 10A 9B 21C 1C 1D
Expected output
1A 1C 1D 1a 9B 10A 21C
Query
Bin Way
===================================
SELECT
tbl_column,
BIN(tbl_column) AS binray_not_needed_column
FROM db_table
ORDER BY binray_not_needed_column ASC , tbl_column ASC
-----------------------
Cast Way
===================================
SELECT
tbl_column,
CAST(tbl_column as SIGNED) AS casted_column
FROM db_table
ORDER BY casted_column ASC , tbl_column ASC
Natural Sorting in MySQL
Given input
Table: sorting_test
-------------------------- -------------
| alphanumeric VARCHAR(75) | integer INT |
-------------------------- -------------
| test1 | 1 |
| test12 | 2 |
| test13 | 3 |
| test2 | 4 |
| test3 | 5 |
-------------------------- -------------
Expected Output
-------------------------- -------------
| alphanumeric VARCHAR(75) | integer INT |
-------------------------- -------------
| test1 | 1 |
| test2 | 4 |
| test3 | 5 |
| test12 | 2 |
| test13 | 3 |
-------------------------- -------------
Query
SELECT alphanumeric, integer
FROM sorting_test
ORDER BY LENGTH(alphanumeric), alphanumeric
Sorting of numeric values mixed with alphanumeric values
Given input
2a, 12, 5b, 5a, 10, 11, 1, 4b
Expected Output
1, 2a, 4b, 5a, 5b, 10, 11, 12
Query
SELECT version
FROM version_sorting
ORDER BY CAST(version AS UNSIGNED), version;
Just do this:
SELECT * FROM table ORDER BY column `name`+0 ASC
Appending the +0 will mean that:
0,
10,
11,
2,
3,
4
becomes :
0,
2,
3,
4,
10,
11
I hate this, but this will work
order by lpad(name, 10, 0) <-- assuming maximum string length is 10
<-- you can adjust to a bigger length if you want to
I know this post is closed but I think my way could help some people. So there it is :
My dataset is very similar but is a bit more complex. It has numbers, alphanumeric data :
1
2
Chair
3
0
4
5
-
Table
10
13
19
Windows
99
102
Dog
I would like to have the '-' symbol at first, then the numbers, then the text.
So I go like this :
SELECT name, (name = '-') boolDash, (name = '0') boolZero, (name+0 > 0) boolNum
FROM table
ORDER BY boolDash DESC, boolZero DESC, boolNum DESC, (name+0), name
The result should be something :
-
0
1
2
3
4
5
10
13
99
102
Chair
Dog
Table
Windows
The whole idea is doing some simple check into the SELECT and sorting with the result.
This works for type of data:
Data1,
Data2, Data3 ......,Data21. Means "Data" String is common in all rows.
For ORDER BY ASC it will sort perfectly, For ORDER BY DESC not suitable.
SELECT * FROM table_name ORDER BY LENGTH(column_name), column_name ASC;
I had some good results with
SELECT alphanumeric, integer FROM sorting_test ORDER BY CAST(alphanumeric AS UNSIGNED), alphanumeric ASC
This type of question has been asked previously.
The type of sorting you are talking about is called "Natural Sorting".
The data on which you want to do sort is alphanumeric.
It would be better to create a new column for sorting.
For further help check
natural-sort-in-mysql
If you need to sort an alpha-numeric column that does not have any standard format whatsoever
SELECT * FROM table ORDER BY (name = '0') DESC, (name+0 > 0) DESC, name+0 ASC, name ASC
You can adapt this solution to include support for non-alphanumeric characters if desired using additional logic.
This should sort alphanumeric field like:
1/ Number only, order by 1,2,3,4,5,6,7,8,9,10,11 etc...
2/ Then field with text like: 1foo, 2bar, aaa11aa, aaa22aa, b5452 etc...
SELECT MyField
FROM MyTable
order by
IF( MyField REGEXP '^-?[0-9]+$' = 0,
9999999999 ,
CAST(MyField AS DECIMAL)
), MyField
The query check if the data is a number, if not put it to 9999999999 , then order first on this column, then order on data with text
Good luck!
Instead of trying to write some function and slow down the SELECT query, I thought of another way of doing this...
Create an extra field in your database that holds the result from the following Class and when you insert a new row, run the field value that will be naturally sorted through this class and save its result in the extra field. Then instead of sorting by your original field, sort by the extra field.
String nsFieldVal = new NaturalSortString(getFieldValue(), 4).toString()
The above means:
- Create a NaturalSortString for the String returned from getFieldValue()
- Allow up to 4 bytes to store each character or number (4 bytes = ffff = 65535)
| field(32) | nsfield(161) |
a1 300610001
String sortString = new NaturalSortString(getString(), 4).toString()
import StringUtils;
/**
* Creates a string that allows natural sorting in a SQL database
* eg, 0 1 1a 2 3 3a 10 100 a a1 a1a1 b
*/
public class NaturalSortString {
private String inStr;
private int byteSize;
private StringBuilder out = new StringBuilder();
/**
* A byte stores the hex value (0 to f) of a letter or number.
* Since a letter is two bytes, the minimum byteSize is 2.
*
* 2 bytes = 00 - ff (max number is 255)
* 3 bytes = 000 - fff (max number is 4095)
* 4 bytes = 0000 - ffff (max number is 65535)
*
* For example:
* dog123 = 64,6F,67,7B and thus byteSize >= 2.
* dog280 = 64,6F,67,118 and thus byteSize >= 3.
*
* For example:
* The String, "There are 1000000 spots on a dalmatian" would require a byteSize that can
* store the number '1000000' which in hex is 'f4240' and thus the byteSize must be at least 5
*
* The dbColumn size to store the NaturalSortString is calculated as:
* > originalStringColumnSize x byteSize + 1
* The extra '1' is a marker for String type - Letter, Number, Symbol
* Thus, if the originalStringColumn is varchar(32) and the byteSize is 5:
* > NaturalSortStringColumnSize = 32 x 5 + 1 = varchar(161)
*
* The byteSize must be the same for all NaturalSortStrings created in the same table.
* If you need to change the byteSize (for instance, to accommodate larger numbers), you will
* need to recalculate the NaturalSortString for each existing row using the new byteSize.
*
* #param str String to create a natural sort string from
* #param byteSize Per character storage byte size (minimum 2)
* #throws Exception See the error description thrown
*/
public NaturalSortString(String str, int byteSize) throws Exception {
if (str == null || str.isEmpty()) return;
this.inStr = str;
this.byteSize = Math.max(2, byteSize); // minimum of 2 bytes to hold a character
setStringType();
iterateString();
}
private void setStringType() {
char firstchar = inStr.toLowerCase().subSequence(0, 1).charAt(0);
if (Character.isLetter(firstchar)) // letters third
out.append(3);
else if (Character.isDigit(firstchar)) // numbers second
out.append(2);
else // non-alphanumeric first
out.append(1);
}
private void iterateString() throws Exception {
StringBuilder n = new StringBuilder();
for (char c : inStr.toLowerCase().toCharArray()) { // lowercase for CASE INSENSITIVE sorting
if (Character.isDigit(c)) {
// group numbers
n.append(c);
continue;
}
if (n.length() > 0) {
addInteger(n.toString());
n = new StringBuilder();
}
addCharacter(c);
}
if (n.length() > 0) {
addInteger(n.toString());
}
}
private void addInteger(String s) throws Exception {
int i = Integer.parseInt(s);
if (i >= (Math.pow(16, byteSize)))
throw new Exception("naturalsort_bytesize_exceeded");
out.append(StringUtils.padLeft(Integer.toHexString(i), byteSize));
}
private void addCharacter(char c) {
//TODO: Add rest of accented characters
if (c >= 224 && c <= 229) // set accented a to a
c = 'a';
else if (c >= 232 && c <= 235) // set accented e to e
c = 'e';
else if (c >= 236 && c <= 239) // set accented i to i
c = 'i';
else if (c >= 242 && c <= 246) // set accented o to o
c = 'o';
else if (c >= 249 && c <= 252) // set accented u to u
c = 'u';
else if (c >= 253 && c <= 255) // set accented y to y
c = 'y';
out.append(StringUtils.padLeft(Integer.toHexString(c), byteSize));
}
#Override
public String toString() {
return out.toString();
}
}
For completeness, below is the StringUtils.padLeft method:
public static String padLeft(String s, int n) {
if (n - s.length() == 0) return s;
return String.format("%0" + (n - s.length()) + "d%s", 0, s);
}
The result should come out like the following
-1
-a
0
1
1.0
1.01
1.1.1
1a
1b
9
10
10a
10ab
11
12
12abcd
100
a
a1a1
a1a2
a-1
a-2
áviacion
b
c1
c2
c12
c100
d
d1.1.1
e
MySQL ORDER BY Sorting alphanumeric on correct order
example:
SELECT `alphanumericCol` FROM `tableName` ORDER BY
SUBSTR(`alphanumericCol` FROM 1 FOR 1),
LPAD(lower(`alphanumericCol`), 10,0) ASC
output:
1
2
11
21
100
101
102
104
S-104A
S-105
S-107
S-111
This is from tutorials point
SELECT * FROM yourTableName ORDER BY
SUBSTR(yourColumnName FROM 1 FOR 2),
CAST(SUBSTR(yourColumnName FROM 2) AS UNSIGNED);
it is slightly different from another answer of this thread
For reference, this is the original link
https://www.tutorialspoint.com/mysql-order-by-string-with-numbers
Another point regarding UNSIGNED is written here
https://electrictoolbox.com/mysql-order-string-as-int/
While this has REGEX too
https://www.sitepoint.com/community/t/how-to-sort-text-with-numbers-with-sql/346088/9
SELECT length(actual_project_name),actual_project_name,
SUBSTRING_INDEX(actual_project_name,'-',1) as aaaaaa,
SUBSTRING_INDEX(actual_project_name, '-', -1) as actual_project_number,
concat(SUBSTRING_INDEX(actual_project_name,'-',1),SUBSTRING_INDEX(actual_project_name, '-', -1)) as a
FROM ctts.test22
order by
SUBSTRING_INDEX(actual_project_name,'-',1) asc,cast(SUBSTRING_INDEX(actual_project_name, '-', -1) as unsigned) asc
This is a simple example.
SELECT HEX(some_col) h
FROM some_table
ORDER BY h
order by len(xxxxx),xxxxx
Eg:
SELECT * from customer order by len(xxxxx),xxxxx
Try this For ORDER BY DESC
SELECT * FROM testdata ORDER BY LENGHT(name) DESC, name DESC
SELECT
s.id, s.name, LENGTH(s.name) len, ASCII(s.name) ASCCCI
FROM table_name s
ORDER BY ASCCCI,len,NAME ASC;
Assuming varchar field containing number, decimal, alphanumeric and string, for example :
Let's suppose Column Name is "RandomValues" and Table name is "SortingTest"
A1
120
2.23
3
0
2
Apple
Zebra
Banana
23
86.Akjf9
Abtuo332
66.9
22
ABC
SELECT * FROM SortingTest order by IF( RandomValues REGEXP '^-?[0-9,.]+$' = 0,
9999999999 ,
CAST(RandomValues AS DECIMAL)
), RandomValues
Above query will do sorting on number & decimal values first and after that all alphanumeric values got sorted.
This will always put the values starting with a number first:
ORDER BY my_column REGEXP '^[0-9]' DESC, length(my_column + 0), my_column ";
Works as follows:
Step1 - Is first char a digit? 1 if true, 0 if false, so order by this DESC
Step2 - How many digits is the number? Order by this ASC
Step3 - Order by the field itself
Input:
('100'),
('1'),
('10'),
('0'),
('2'),
('2a'),
('12sdfa'),
('12 sdfa'),
('Bar nah');
Output:
0
1
2
2a
10
12 sdfa
12sdfa
100
Bar nah
Really problematic for my scenario...
select * from table order by lpad(column, 20, 0)
My column is a varchar, but has numeric input (1, 2, 3...) , mixed numeric (1A, 1B, 1C) and too string data (INT, SHIP)