Select all columns with ascii code in mysql - mysql

I have a code which I recently discovered :) and it does do its job and well done I might add. But, I want to check all columns instead of checking it by column. Is it possible
Check my code below:
SELECT column_name
FROM table_name
WHERE column_name REGEXP '[[.DLE.]-[.US.]]'
Now, what I want is something like this but it won't work
SELECT *
FROM table_name
WHERE REGEXP '[[.DLE.]-[.US.]]'
Kindly advice and I apologize for asking many questions :)

REGEXP is a binary operator which means you have to have a left operand and a right operand.
Like most arithmetic operators.
You could check all columns like this:
SELECT *
FROM table_name
WHERE CONCAT(a, b, c, d, ...) REGEXP '[[.DLE.]-[.US.]]'
I'm using ... for the sake of the example, but you'd need to name all your columns explicitly. There's no option to use a wildcard for the columns inside an expression.
You can't set "all columns" in a single SET clause. You'd need to do something like the following:
UPDATE table_name SET
a = REPLACE(a,char(16),''),
b = REPLACE(b,char(16),''),
c = REPLACE(c,char(16),''),
d = REPLACE(d,char(16),''),
...similar for other columns;
If you think this is an unexpected omission in the SQL language, then I wonder if you can name any other programming language that lets you compare to or assign a value to "all variables" in a single expression?

Related

Regex bring just the match MySQL

I am trying to getting just the first two words on sql query, I am using the match: ^\w{2}- but with no success because nothing is coming to me, I need to get those values
BA, CE, DF, ES, GO, I don't know how can I do that, below some data example.
SC&Tipo=FM
SC&Tipo=Web
SC&Tipo=Comunitaria
RS&Tipo=Todas
RS&Tipo=AM
RS&Tipo=FM
RS&Tipo=Web
RS&Tipo=Comunitaria
BA-Salvador&Tipo=12horas
CE-Fortaleza&Tipo=12horas
CE-Interior&Tipo=12horas
DF-Brasilia&Tipo=12horas
ES-Interior&Tipo=12horas
ES-Vitoria&Tipo=12horas
GO-Goiania&Tipo=12horas
MG-ZonaDaMata/LestedeMinas&Tipo=12horas
MG-AltoParanaiba&Tipo=12horas
MG-BeloHorizonte&Tipo=12horas
MG-CentroOestedeMinas&Tipo=12horas
Query: SELECT * FROM tabel WHERE filter REGEXP '^\w{2}-'
EDIT SOLVED:
To solve the query should be:
SELECT SUBSTRING(column, 1, 2) AS column FROM table WHERE column REGEXP '^[[:alnum:]_]{2}-'
MySQL doesn't support the character class \w or \d. Instead of \w you have to use [[:alnum:]]. You can find all the supported character classes on the official MySQL documentation.
So you can use the following solution using REGEXP:
SELECT *
FROM table_name
WHERE filter REGEXP '^[[:alnum:]]{2}-'
You can use the following to get the result with regular expression too, using REGEXP_SUBSTR:
SELECT REGEXP_SUBSTR(filter, '^[[:alnum:]]{2}-')
FROM table_name
WHERE filter REGEXP '^[[:alnum:]]{2}-';
Or another solution using HAVING to filter the result:
SELECT REGEXP_SUBSTR(filter, '^[[:alnum:]]{2}-') AS colResult
FROM table_name
HAVING colResult IS NOT NULL;
To get the value before MySQL 8.0 you can use the following with LEFT:
SELECT LEFT(filter, 3)
FROM table_name
WHERE filter REGEXP '^[[:alnum:]]{2}-';
demo: https://www.db-fiddle.com/f/7mJEmCkEiYhCYK3PcEZTNE/0
Using SUBSTRING(<column>, 1, 2) should also work..
More or less like below
SELECT
<column>
, SUBSTRING(<column>, 1, 2)
FROM
<table>
WHERE
SUBSTRING(<column>, 1, 2) IN ('BA' [,<value>..])
Some things are BNF (Backus-Naur form) in the SQL code.
<..> means replace with what you need.
[, ..] means optional unlimited repeat the comma in there is part off SQL syntax

Can anyone tell me in mysql How to display employee names whose name DO NOT start with alphabet A?

I am a beginner so please help me.
There are 2 things you need to combine in this case.
Because you didn't provide enough information in your question we have to guess what you mean by name. I'm going to assume that you have a single name column, but that would be unusual.
With strings, to match a character column that is not an exact match, you need to use LIKE which allows for wildcards.
You also need to negate the match, or in other words show things that are NOT (something).
First to match names that START with 'A'.
SELECT * FROM table_name WHERE name LIKE 'A%';
This should get you all the PEOPLE who have names that "Start with A".
Some databases are case sensitive. I'm not going to deal with that issue. If you were using MySQL that is not an issue. Case sensitivity is not universal. In some RDBMS like Oracle you have to take some steps to deal with mixed case in a column.
Now to deal with what you actually want, which is NOT (starting with A).
SELECT * FROM table_name WHERE name NOT LIKE 'A%';
your question should have more detail however you can use the substr function
SELECT name FROM yourtable
WHERE SUBSTR(name,1,1) <> 'A'
complete list of mysql string functions here
mysql docs
NOT REGXP operator
MySQL NOT REGXP is used to perform a pattern match of a string expression expr against a pattern pat. The pattern can be an extended regular expression.
Syntax:
expr NOT REGEXP pat
Query:
SELECT * FROM emp_table WHERE emp_name NOT REGEXP '^[a]';
or
SELECT * FROM emp_table WHERE emp_name NOT REGEXP '^a';

Oracle SQL - Regex to search columns with only 1 letter

I want to to create a regex to find all columns that only have a single character ([A-Z]) as name, like N or M but not NM.
I've tried:
SELECT * FROM 'table' WHERE Name REGEXP '^[A-Z]'
But it's not displaying the expected result.
Try ^[A-Z]$.
You then state that this character is first and also last character of the value.
The regex functions in Oracle work only on one column. So, to search for just one character in a column, you would do the following:
select * from yourTable where REGEXP_LIKE (col1, '^[A-z]$');
Now, to search all the char/varchar columns on your table, you'll need to chain the regex expressions together, like so:
select * from yourTable where REGEXP_LIKE (col1, '^[A-z]$') or REGEXP_LIKE (col3, '^[A-z]$');
SQL solution:
where name in ('N','M')

MySQL LIke statement - multiple words

What would be the right SQL statement so that when I search two words, like for example 'text field' in a text box, it will return all results that has 'text' and 'field' in it using the LIKE statement? I cant find the right terms to make a search. If possible, I want to make it dynamic. Like if a user search 5 words, all 5 words would be in the Like statement. I am trying to achieve a statement something like this.
SELECT *
FROM TABLE
WHERE SEARCH (LIKE %searchterm1%)
OR (LIKE %searchterm2%)
OR (LIKE %searchterm3%) ....
Try This. http://dev.mysql.com/doc/refman/5.1/en/regexp.html#operator_regexp
SELECT *
FROM TABLE
WHERE SEARCH
REGEXP 'searchterm1|searchterm2|searchterm3'
Here's an example of a SQL SELECT statement that uses the LIKE comparison operator
SELECT t.*
FROM mytable t
WHERE t.col LIKE CONCAT('%','cdef','%')
AND t.col LIKE CONCAT('%','hijk','%')
AND t.col LIKE CONCAT('%','mnop','%')
Only rows that have a value in the col column that contains all of the strings 'cdef', 'hijk', and 'mnop' will be returned.
You specifically asked about the LIKE comparison operator. There's also a REGEXP operator that matches regular expressions. And the Full-Text search feature may be a good fit your use case.

MySQL Remove characters from column headers

All my column headers in a MySQL database are prefixed with a number, 1_X, 2_X, etc... which makes bringing the data into IDL impossible using just a basic select statement to bring in the entire table. I'm not sure but I see two possible ways:
1) Bring in the table with column name aliases. Can I use TRIM or SUBSTRING_INDEX to remove/replace the first two characters?
2) Create a routine that uses the information schema to to recursively go through and delete the first two characters of the column headers and create a new table with those headers and copy the data in.
If there weren't so many different tables (all with 1_X, 2_X, etc...) there'd be no problem manually selecting 1_X AS X but that's not feasible. It would be great to be able to use TRIM/SUBSTRING on column headers in the select statement.
Thanks.
It's not possible to use functions in a SQL statement to alter the identifier assigned to a column being returned. The SQL way of specifying the identifier for the column in a resultset is to use the expr AS alias approach.
Rather than trim off the leading digit characters, you could prepend the identifiers with another valid character. (Trimming off leading characters seems like it would potentially lead to another problem, duplicate and/or zero length column names.)
You could just use a SQL statement to generate the SELECT list for you.
(NOTE: the GROUP_CONCAT function is limited by some system/session variables: group_concat_max_len and max_allowed_packet, it's easy enough to adjust these higher, though changing global max_allowed_packet may require MySQL to be restarted.)
To get it back the SELECT list on all one line (assuming you won't overflow the GROUP_CONCAT limits) something like:
SELECT c.table_schema
, c.table_name
, GROUP_CONCAT(
CONCAT('t.`',c.column_name,'` AS `x',c.column_name,'`')
ORDER BY c.ordinal_position
) AS select_list_expr
FROM information_schema.columns c
FROM information_schema.columns c
WHERE c.table_schema = 'mydatabase'
GROUP BY c.table_schema, c.table_name
Or, you could even get back a whole SELECT statement, if you wrapped that GROUP_CONCAT expression (which produces the select list) in another CONCAT
Something like this:
SELECT CONCAT('SELECT '
, GROUP_CONCAT(
<select_list_expr>
)
, ' FROM `',c.table_schema,'`.`',c.table_name,'` t;'
) AS stmt
FROM information_schema.columns c
WHERE c.table_schema = 'mydatabase'
GROUP BY c.table_schema, c.table_name
You could use a more clever expression for <select_list_expr>, to check for leading "digit" characters, and assign an alias to just those columns that need it, and leave the other columns unchanged, though that again introduces the potential for returning duplicate column names.
That is, if you already have columns named '1_X' and 'x1_X' in the same table. But a carefully chosen leading character may avoid that problem...
The <select_list_expr> could be more clever by doing a conditional test for leading digit character, something like this:
SELECT CONCAT('SELECT '
, GROUP_CONCAT(
CASE
WHEN c.column_name REGEXP '^[[:digit:]]'
THEN CONCAT('t.`',c.column_name,'` AS `x',c.column_name,'`')
ELSE CONCAT('t.`',c.column_name,'`')
END
)
, ' FROM `',c.table_schema,'`.`',c.table_name,'` t;'
) AS stmt
FROM information_schema.columns c
WHERE c.table_schema = 'mydatabase'
GROUP BY c.table_schema, c.table_name
Again, there's a potential for generation "duplicate" column names with this approach. The conditional test "c.column_name REGEXP" could be extended to check for other "invalid" leading characters as well.
As a side note, at some point, someone thought it a "good idea" to name columns with leading digit characters. Just because something is allowed doesn't mean it's a good idea.
Then again, maybe all that rigamarole isn't necessary, and just wrapping the column names in backticks would be sufficient for your application.
I think you can follow option 2. However this will not be quick solution.
Another way around this could be,
Generate schema script for the tables you want to correct.
Open the script in notepad++ or any editor that supports find using regular expression.
Search and replace with [0-9]+_ expression and empty string for replacement.
Create the new tables using this script and copy data into them.
This may sound like a manual approach but you will do this once for all of your tables.
Look into a strategy of doing 2 selects, one for the column name, then one for the data with column alias. You might have to revert to some scripting language, like PHP, for help.
First, get the column names :
show columns from tbl_client;
+-------------------------------+-----------------------------------+------+-----+---------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+-------------------------------+-----------------------------------+------+-----+---------------------+-----------------------------+
| 1_X | int(11) | NO | PRI | NULL | auto_increment |
Then, loop through the results and create a list of column alias
Then create your new select
SELECT 1_X as NEW_COLUMN_NAME_FOR_FIELD_1 FROM tbl_client;