26

I have a table with a column containing data that begin with numbers too, on MySQL

How can I select the rows that begin only with a number?

codaddict
  • 445,704
  • 82
  • 492
  • 529
Omega
  • 8,640
  • 9
  • 30
  • 29
  • Same general sentiment as this thread on how to [Detect if value is number in MySQL](https://stackoverflow.com/q/5064977/1366033), but just restricted to the first char – KyleMit Dec 22 '17 at 19:23

5 Answers5

47
SELECT * FROM YourTable WHERE YourColumn regexp '^[0-9]+'
Sarfraz
  • 377,238
  • 77
  • 533
  • 578
13

Yet another way:

WHERE LEFT(columnName,1) IN ('0','1','2','3','4','5','6','7','8','9')

and with common charsets and collations, this would work and use an index on the column:

WHERE columnName >= '0' AND columnName < ':'
ypercubeᵀᴹ
  • 113,259
  • 19
  • 174
  • 235
10

You can do:

SELECT *
FROM MyTable
WHERE MyColumn REGEXP '^[0-9]';

The regular expression used is ^[0-9].

^    - Start anchor, used to ensure the pattern matches start of the string.
[    - Start of character class.
0-9  - Any digit
]    - End of character class

Effectively we are trying to select those values in the column that begin with a digit.

Demo:

mysql> select * from tab;
+-------+
| col   |
+-------+
| 1foo  |
| foo   |
| 10foo |
| foo10 |
+-------+
4 rows in set (0.00 sec)

mysql> select * from tab where col regexp '^[0-9]';
+-------+
| col   |
+-------+
| 1foo  |
| 10foo |
+-------+
2 rows in set (0.00 sec)
codaddict
  • 445,704
  • 82
  • 492
  • 529
6

also

SELECT * FROM YourTable
WHERE YourColumn LIKE '[0-9]%';
Lukas Greso
  • 472
  • 4
  • 6
  • 2
    `SELECT * FROM \`artists\` WHERE \`artist\` LIKE '[0-9]%'` returns empty. – akinuri Jul 06 '16 at 23:22
  • 2
    MySQL's `like` does not support such patterns. You have to use `regexp` for that. e.g.: `SELECT * FROM foo WHERE bar REGEXP '^[0-9]'`. https://dev.mysql.com/doc/refman/5.7/en/pattern-matching.html – Tristan Jahier Mar 22 '17 at 19:31
2
SELECT * FROM TABLE T
WHERE T.COLUMNNAME REGEXP '^[0-9]';

Another answer is:

SELECT * FROM TABLE T
WHERE T.COLUMNNAME RLIKE '^[0-9]';
Vasily Kabunov
  • 6,511
  • 13
  • 49
  • 53
Vaibhav Kumar
  • 544
  • 5
  • 17