MySQL - If It Starts With A Number Or Special Character - mysql

SELECT *
FROM `thread`
WHERE forumid NOT IN (1,2,3) AND IF( LEFT( title, 1) = '#', 1, 0)
ORDER BY title ASC
I have this query which will select something if it starts with a #. What I want to do is if # is given as a value it will look for numbers and special characters. Or anything that is not a normal letter.
How would I do this?

If you want to select all the rows whose "title" does not begin with a letter, use REGEXP:
SELECT *
FROM thread
WHERE forumid NOT IN (1,2,3)
AND title NOT REGEXP '^[[:alpha:]]'
ORDER BY title ASC
NOT means "not" (obviously ;))
^ means "starts with"
[[:alpha:]] means "alphabetic characters only"
Find more about REGEXP in MySQL's manual.

it's POSSIBLE you can try to cast it as a char:
CAST('#' AS CHAR)
but i don't know if this will work for the octothorpe (aka pound symbol :) ) because that's the symbol for starting a comment in MySQL

SELECT t.*
FROM `thread` t
WHERE t.forumid NOT IN (1,2,3)
AND INSTR(t.title, '#') = 0
ORDER BY t.title
Use the INSTR to get the position of a given string - if you want when a string starts, check for 0 (possibly 1 - the documentation doesn't state if it's zero or one based).

Related

MySQL: Limit the number of characters in LIKE clause?

I'm using this query in my autocomplete feature:
SELECT description FROM my_table WHERE LIKE "%keyword%"
But this query returns the entire content of the field which is sometimes too long.
Is it possible to limit the number of characters before and after "keyword" ?
I suggest using MySQL's REGEXP operator here. For example, to accept a maximum of 10 characters before and after keyword, you could use:
SELECT description
FROM my_table
WHERE col REGEXP '^.{0,10}keyword.{0,10}$';
Note that if you intend to match keyword as a standalone word, you may want to surround it by word boundaries in the regex pattern:
SELECT description
FROM my_table
WHERE col REGEXP '^.{0,10}\\bkeyword\\b.{0,10}$';
To show for example 5 characters before and after you word you can do it using RIGHT, LEFT and SUBSTRING_INDEX
select description, concat(RIGHT(SUBSTRING_INDEX(description, 'keyword', 1),5), 'keyword', LEFT(SUBSTRING_INDEX(description, 'keyword', -1),5) ) as snippet
from my_table
where description like "%keyword%";
Check it here : https://dbfiddle.uk/MZcVJgEL

SELECT to match special characters and case

Field X in table may contain special characters e.g hello!World and I would like to know if there is a way to match that with HelloWorld (Ignore case and special characters).
SELECT * FROM table WHERE X='Helloworld'
http://sqlfiddle.com/#!9/2afa1/1
if you need exaclty match of string:
SELECT *
FROM table1
WHERE x REGEXP '^hello[[:punct:],[:space:]]world$';
And if hello world could be a part of larger string:
SELECT *
FROM table1
WHERE x REGEXP 'hello[[:punct:],[:space:]]world';
What you can do is to replace all special characters like this:
SELECT * FROM table WHERE LOWER(REPLACE(X, '!', '')) = LOWER('HelloWorld');
Chain those replacements if you have to replace more:
SELECT * FROM table WHERE LOWER(REPLACE(REPLACE(X, '!', ''), '?', '')) = LOWER('HelloWorld');
If I understood your question right, you need to filter out non-ASCII characters? Please confirm whether this is true. In order to do that, have a look at REGEXP matching as in the comment link and this question.
Try something like
SELECT * FROM `table ` WHERE `X` REGEXP 'Helloworld';
REGEXP 'hello[^[:alpha:]]*world'
Notes:
This finds the string in the middle of other stuff; add ^ and $ to anchor to ends.
This assumes the non-alpha character(s) are between hello and world, not some other spot in the string.
This relies on the relevant collation to do (or not do) case folding.

Order by last 3 chars

I have a table like:
id name
--------
1 clark_009
2 clark_012
3 johny_002
4 johny_010
I need to get results in this order:
johny_002
clark_009
johny_010
clark_012
Do not ask me what I already tried, I have no idea how to do this.
This will do it, very simply selecting the right-most 3 characters and ordering by that value ascending.
SELECT *
FROM table_name
ORDER BY RIGHT(name, 3) ASC;
It should be added that as your data grows, this will become an inefficient solution. Eventually, you'll probably want to store the numeric appendix in a separate, indexed integer column, so that sorting will be optimally efficient.
you should try this.
SELECT * FROM Table order by SUBSTRING(name, -3);
good luck!
You may apply substring_index function to parse these values -
select * from table order by substring_index(name, '_', -1)
You can use MySQL SUBSTRING() function to sort by substring
Syntax : SUBSTRING(string,position,length)
Example : Sort by last 3 characters of a String
SELECT * FROM TableName ORDER BY SUBSTRING(FieldName, -3);
#OR
SELECT * FROM TableName ORDER BY SUBSTRING(FieldName, -3,3);
Example : Sort by first 3 characters of a String
SELECT * FROM TableName ORDER BY SUBSTRING(FieldName, 1,3);
Note : Positive Position/Index start from Left to Right and Negative Position/Index start from Right to Left of the String.
Here is the details about SUBSTRING() function.
If you want to order by the last three characters (from left to right) with variable name lengths, I propose this:
SELECT *
FROM TABLE
ORDER BY SUBSTRING (name, LEN(name)-2, 3)
The index starts at lenght of name -2 which is the third last character.
I'm a little late but just encountered the same problem and this helped me.

MySQL regex query case insensitive

In my table I have firstname and last name. Few names are upper case ( ABRAHAM ), few names are lower case (abraham), few names are character starting with ucword (Abraham).
So when i am doing the where condition using REGEXP '^[abc]', I am not getting proper records. How to change the names to lower case and use SELECT QUERY.
SELECT * FROM `test_tbl` WHERE cus_name REGEXP '^[abc]';
This is my query, works fine if the records are lower case, but my records are intermediate ,my all cus name are not lower case , all the names are like ucword.
So for this above query am not getting proper records display.
I think you should query your database making sure that the names are lowered, suppose that name is the name you whish to find out, and in your application you've lowered it like 'abraham', now your query should be like this:
SELECT * FROM `test_tbl` WHERE LOWER(cus_name) = name
Since i dont know what language you use, I've just placed name, but make sure that this is lowered and you should retrieve Abraham, ABRAHAM or any variation of the name!
Hepe it helps!
Have you tried:
SELECT * FROM `test_tbl` WHERE LOWER(cus_name) REGEXP '^[abc]';
I don't know since when, but nowadays MySql REGEXP is case insensitive.
https://dev.mysql.com/doc/refman/5.7/en/pattern-matching.html
You don't need regexp to search for names starting with a specific string or character.
SELECT * FROM `test_tbl` WHERE cus_name LIKE 'abc%' ;
% is wildcard char. The search is case insensitive unless you set the binary attribute for column cus_name or you use the binary operator
SELECT * FROM `test_tbl` WHERE BINARY cus_name LIKE 'abc%' ;
A few valid options already presented, but here's one more with just regex:
SELECT * FROM `test_tbl` WHERE cus_name REGEXP '^[abcABC]';

MySQL query for alphabetical search

How to retrieve the records those character star starting with A OR B OR C ,
I just tried this query
SELECT * FROM `test_tbl` WHERE Left(cus_name, 1) = 'a'
---> display all customer name starting with character a
AND I added one more condition, That is
SELECT * FROM `test_tbl` WHERE Left(cus_name, 1) = 'a' or Left(cus_name, 1) = 'b'
--->It displayed all customer name starting with character a and in some records middle i saw some name starting with b also,
What i want is , i want pull out records , which names are starting with A or B or C ,
And also it should order by alphabetical order,
Also i tried this below query.
SELECT * FROM `test_tbl` WHERE Left(cus_name, 1) REGEXP '^[^a-z]+$';
The rendered records for that above is , just two records started with A,
This above question for doing the alphabetical pagination ,
Thanks
You can try:
SELECT * FROM `test_tbl` WHERE cus_name REGEXP '^[abc]';
It will list all rows where cus_name starts with either a, b or c.
The regex used is ^[abc]:
^ : Is the start anchor
[..] : Is the character class. So [abc] matches either an a or a b or a c. It is equivalent to (a|b|c)
The regex you were using : ^[^a-z]+$
The first ^ is the start anchor.
[..] is character class.
The ^ inside the character class
negates it. So [^abc] is any
character other than the three
listed.
+ is the quantifier for one or
more.
$ is the end anchor.
So effectively you are saying: give me all the rows where cus_name contains one or more letters which cannot be any of the lowercase letters.
try like instead
SELECT * FROM `test_tbl` WHERE cus_name like 'a%'