I have these rows:
db666405.gallery
db666405.table1
db666405.table2
I want to capture the word after the dot.
How to do with regex in mysql?
I have tried with ^\. or [.], but I did not succeed.
SELECT *
FROM `table`
WHERE `column` REGEXP '^\\.'
MySQL regex doesn't "capture" anything. It's for matching only; there is no support for regex replacement in MySQL.
I assume you want to return the part after the dot:
select *, substring(`column`, instr(`column`, '.') + 1) as ext
from `table`
where `column` like '%.?%'
To select any columns that have the word Gallery, you can use a
SELECT *
FROM `table`
WHERE `column` LIKE '%gallery%' `
This will return all that have gallery
I would like to use REGEXP in a CASE WHEN context like this:
SELECT
CASE title
WHEN REGEXP '^(The Matrix|Riddick|American Pie)$' THEN (
'Movie'
) ELSE (
'FOOO'
)
END
FROM `movies`
but this is not possible. I would like to match different strings here as you can see.
Regards,
Felix
This is indeed possible, with the correct syntax. REGEXP requires a left and right side operand, so use the other syntax of CASE where the full expression is placed after WHEN.
SELECT
CASE
WHEN `title` REGEXP '^(The Matrix|Riddick|American Pie)$' THEN 'Movie'
ELSE 'FOOO'
END AS column_alias
FROM `movies`
However, if you are not using any variable elements in the regular expression, this is likely to be far less efficient than doing exact matches on an indexed column. In other words, you have no need for a regular expression with the example you gave.
SELECT
CASE
WHEN `title` IN ('The Matrix', 'Riddick') THEN 'Movie'
ELSE 'FOOO'
END AS your_column_alias
FROM `movies`
In a perfect world for this type of setup, we would have an integer column that expects only numbers;
But what if you have a varchar column and you want to add a WHERE clause that said something like this:
WHERE <value> is NOT a number
In essence, you are selecting all rows that contain any characters that are NOT ONLY numbers.
This is for MySQL.
try this
SELECT * FROM myTable WHERE concat('',col1 * 1) != col1
demo here
REGEXP or RLIKE are your friends:
SELECT * FROM `MyTable` WHERE `Column` RLIKE '^[^0-9]*$';
UPDv1:
You may use different regexes to detect negative integers:
SELECT
'-2' RLIKE '^[^0-9]*$', -- fails
'-1' RLIKE '-[0-9]'; -- succeeds
For example:
SELECT * FROM `MyTable` WHERE `Column` RLIKE '-[0-9]' OR `Column` RLIKE '^[^0-9]*$';
Tested with this:
SELECT
*
FROM
(
SELECT 'abs 12 x' as `Column`
UNION ALL
SELECT 12
UNION ALL
SELECT -2
UNION ALL
SELECT '-x'
) as `sub`
WHERE
`Column` RLIKE '-[0-9]'
OR
`Column` RLIKE '^[^0-9]*$';
Output:
-2
-x
You should be able to use a regular expression in the where clause.
The following mysql documentation link provides details:
http://dev.mysql.com/doc/refman/5.1/en/regexp.html
This would approach somehow your goal:
SELECT * FROM MyTable WHERE NOT MyTable.Field1 REGEXP '^[[:digit:]]*$';
As Field1 is VARCHAR, this will select all rows that Field1 is not wholly numerical.
If you have floating-point value:
SELECT * FROM MyTable WHERE NOT MyTable.Field1 REGEXP '^[[:digit:]\.]*$';
I want to select rows from a table if a column contains a certain number e.g 981. The data in these columns is either 0, null or in the format below:
1007,1035,1189,908,977,974,979,973,982,981,1007
How do I phrase this in a query?
Obvious this query below isn't sufficient but I need something similar
SELECT * FROM `table` WHERE `column`='981'
Thanks
If you have regular expressions it may work:
SELECT * FROM `table` WHERE `column` REGEXP '(^|,)951($|,)'
You can use the IN clause which checks whether a value is within a set of values.
SELECT * FROM `table` WHERE `column` IN (1007,1035,1189,979,973,982,981,1007)
or
SELECT * FROM `table` WHERE `column` IN ('abc','def','ghi')
Please note that cannot mix quoted and unquoted values in the IN list
EDIT
I misunderstood the original question. If your column data is like 1007,1035,1189,979,973,982,981,1007 and you're searching for the presence of 981 then you'll have to use LIKE instead of IN
SELECT * FROM table WHERE (column LIKE ('%,981,%') OR column LIKE ('%,981') OR column LIKE ('981,%'))
to pattern match the value 981 in the middle, at the end or at the beginning of those comma separated values.
I have a column in a table which might contain null or empty values. How do I check if a column is empty or null in the rows present in a table?
(e.g. null or '' or ' ' or ' ' and ...)
This will select all rows where some_col is NULL or '' (empty string)
SELECT * FROM table WHERE some_col IS NULL OR some_col = '';
As defined by the SQL-92 Standard, when comparing two strings of differing widths, the narrower value is right-padded with spaces to make it is same width as the wider value. Therefore, all string values that consist entirely of spaces (including zero spaces) will be deemed to be equal e.g.
'' = ' ' IS TRUE
'' = ' ' IS TRUE
' ' = ' ' IS TRUE
' ' = ' ' IS TRUE
etc
Therefore, this should work regardless of how many spaces make up the some_col value:
SELECT *
FROM T
WHERE some_col IS NULL
OR some_col = ' ';
or more succinctly:
SELECT *
FROM T
WHERE NULLIF(some_col, ' ') IS NULL;
A shorter way to write the condition:
WHERE some_col > ''
Since null > '' produces unknown, this has the effect of filtering out both null and empty strings.
Please mind: the best practice it at the end of the answer.
You can test whether a column is null or is not null using WHERE col IS NULL or WHERE col IS NOT NULL e.g.
SELECT myCol
FROM MyTable
WHERE MyCol IS NULL
In your example you have various permutations of white space. You can strip white space using TRIM and you can use COALESCE to default a NULL value (COALESCE will return the first non-null value from the values you suppy.
e.g.
SELECT myCol
FROM MyTable
WHERE TRIM(COALESCE(MyCol, '')) = ''
This final query will return rows where MyCol is null or is any length of whitespace.
If you can avoid it, it's better not to have a function on a column in the WHERE clause as it makes it difficult to use an index. If you simply want to check if a column is null or empty, you may be better off doing this:
SELECT myCol
FROM MyTable
WHERE MyCol IS NULL OR MyCol = ''
See TRIM COALESCE and IS NULL for more info.
Also Working with null values from the MySQL docs
Another method without WHERE, try this..
Will select both Empty and NULL values
SELECT ISNULL(NULLIF(fieldname,'')) FROM tablename
Either
SELECT IF(field1 IS NULL or field1 = '', 'empty', field1) as field1 from tablename
or
SELECT case when field1 IS NULL or field1 = ''
then 'empty'
else field1
end as field1 from tablename
This statement is much cleaner and more readable for me:
select * from my_table where ISNULL(NULLIF(some_col, ''));
try
SELECT 0 IS NULL , '' IS NULL , NULL IS NULL
-> 0, 0, 1
or
SELECT ISNULL(' ') , ISNULL( NULL )
-> 0 ,1
Reference
I hate messy fields in my databases. If the column might be a blank string or null, I'd rather fix this before doing the select each time, like this:
UPDATE MyTable SET MyColumn=NULL WHERE MyColumn='';
SELECT * FROM MyTable WHERE MyColumn IS NULL
This keeps the data tidy, as long as you don't specifically need to differentiate between NULL and empty for some reason.
While checking null or Empty value for a column in my project, I noticed that there are some support concern in various Databases.
Every Database doesn't support TRIM method.
Below is the matrix just to understand the supported methods by different databases.
The TRIM function in SQL is used to remove specified prefix or suffix from a string. The most common pattern being removed is white spaces. This function is called differently in different databases:
MySQL: TRIM(), RTRIM(), LTRIM()
Oracle: RTRIM(), LTRIM()
SQL Server: RTRIM(), LTRIM()
How to Check Empty/Null :-
Below are two different ways according to different Databases-
The syntax for these trim functions are:
Use of Trim to check-
SELECT FirstName FROM UserDetails WHERE TRIM(LastName) IS NULL
Use of LTRIM & RTRIM to check-
SELECT FirstName FROM UserDetails WHERE LTRIM(RTRIM(LastName)) IS NULL
Above both ways provide same result just use based on your DataBase support. It Just returns the FirstName from UserDetails table if it has an empty LastName
Hoping this will help you :)
If you want to have NULL values presented last when doing an ORDER BY, try this:
SELECT * FROM my_table WHERE NULLIF(some_col, '') IS NULL;
You can also do
SELECT * FROM table WHERE column_name LIKE ''
The inverse being
SELECT * FROM table WHERE column_name NOT LIKE ''
SELECT * FROM tbl WHERE trim(IFNULL(col,'')) <> '';
My two cents.
In MySQL you can use the COALESCE function:
Returns the first non-NULL value in the list, or NULL if there are no non-NULL values.
So you can simplify your query like this:
SELECT * FROM table WHERE COALESCE(some_col, '') = '';
select * from table where length(RTRIM(LTRIM(column_name))) > 0
The below SQL query works fine.
SELECT * FROM <table-name> WHERE <column-name> IS NULL;
In my case, space was entered in the column during the data import and though it looked like an empty column its length was 1. So first of all I checked the length of the empty looking column using length(column) then based on this we can write search query
SELECT * FROM table WHERE LENGTH(column)=0;
Check for null
$column is null
isnull($column)
Check for empty
$column != ""
However, you should always set NOT NULL for column,
mysql optimization can handle only one IS NULL level
try this if the datatype are string and row is null
SELECT * FROM table WHERE column_name IS NULL OR column_name = ''
if the datatype are int or column are 0 then try this
SELECT * FROM table WHERE column_name > = 0
Get rows with NULL, 0, '', ' ', ' '
SELECT * FROM table WHERE some_col IS NOT TRUE;
Get rows without NULL, 0, '', ' ', ' '
SELECT * FROM table WHERE some_col IS TRUE;
SELECT column_name FROM table_name WHERE column_name IN (NULL, '')