Select values that begin with a number

105,035

Solution 1

SELECT * FROM YourTable WHERE YourColumn regexp '^[0-9]+'

Solution 2

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)

Solution 3

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 < ':'

Solution 4

also

SELECT * FROM YourTable
WHERE YourColumn LIKE '[0-9]%';

Solution 5

SELECT * FROM TABLE T
WHERE T.COLUMNNAME REGEXP '^[0-9]';

Another answer is:

SELECT * FROM TABLE T
WHERE T.COLUMNNAME RLIKE '^[0-9]';
Share:
105,035

Related videos on Youtube

Omega
Author by

Omega

Updated on July 09, 2022

Comments

  • Omega
    Omega almost 2 years

    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?

  • Brad Christie
    Brad Christie over 13 years
    +1 for REGEXP (I don't think LIKE supports RegEx (as @RedFilter) has implied). Though, I would probably use '^[0-9]+' as a pattern myself.
  • Magendran V
    Magendran V about 9 years
    Do I need to add any assembly or something to use REGEXP in MS SQL server?
  • Redone
    Redone almost 9 years
    Hey can you post the sqlite version for the query above because regexp in not available in some android devices. Thanks in advance
  • malyy
    malyy almost 8 years
    you may also use rlike instead of like
  • akinuri
    akinuri almost 8 years
    SELECT * FROM `artists` WHERE `artist` LIKE '[0-9]%' returns empty.
  • Tristan Jahier
    Tristan Jahier about 7 years
    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]'. dev.mysql.com/doc/refman/5.7/en/pattern-matching.html
  • jave.web
    jave.web about 7 years
    "RLIKE is a synonym for REGEXP"
  • Alex78191
    Alex78191 almost 5 years
    whyn not '^[0-9].+'?