LIKE '[charlist]%' syntax not working in MySQL (phpMyAdmin) - mysql

There is table named Students. I want to extract the names of students whose name starts with either 'n' or 'p' or 'y'. I know that in TSQL (MS SQL server) I can write the query as follows and it works:
SELECT * FROM Students WHERE StudentName LIKE '[npy]%'
But when I execute the same query in MySQL (phpmyadmin) I was unable to retrieve the correct result set. I tried converting the letters of the student name into the same case which is mentioned in the charlist. I did bit of googling and found out that in MySQL we need to specify this as a regular expression. I executed the below query and got the expected result.
SELECT * FROM Students WHERE StudentName REGEXP '[[:<:]]n | [[:<:]]p | [[:<:]]y'
I want to know the reason why LIKE '[charlist]%' syntax is not working with MySQL. Is it due to the implementation in MySQL (MySQL doesn't support the syntax) or something wrong with the phpmyadmin version I'm using?
Any help regarding this is highly appreciated. Thanks :)

There is an even shorter way to write your query:
SELECT * FROM Students WHERE StudentName REGEXP '^[npy]'
And if you're concerned about being case sensitive:
SELECT * FROM Students WHERE StudentName REGEXP BINARY '^[npy]'
In MySQL, a REGEXP pattern match succeeds anywhere in the value, which differs from LIKE where the pattern must match the entire value.
The following link will give you a more complete answer:
MySQL Pattern Matching

MySQL :
Case insensitive: SELECT * FROM Students WHERE StudentName RLIKE '^[npy]' ;
Case sensitive : SELECT * FROM Students WHERE StudentName CAST(RLIKE as BINARY) '^[npy]' ;

Related

Select records from table where column value is contained in string (mysql with ActiveRecord)

Say I have a table called books with a column in it called keyword.
Say I also have a string called words.
I want to select all records from books where the column keyword is included in words.
I can do this using LIKE directly in mysql.
I'm trying to translate this into an ActiveRecord query for a rails app if anyone could give me a hand with the syntax.
The tricky part is that I want to find records where the column value is included in my string, not the other way around. Very similar to this question, except I need to translate it to ActiveRecord.
SQL - Query to find if a string contains part of the value in Column
Here is a working sql query that I am trying to translate.
SELECT * FROM books WHERE "new science fiction" LIKE CONCAT('%',keyword,'%');
In the above example "new science fiction" is the string words.
Say I have 3 book records. book1 has keyword 'science', book2 has keyword 'fiction' and book3 has keyword 'other'. My above query would return the records book1 and book2. Because 'science' and 'fiction' are included in the words string 'new science fiction'.
My SQL query works but I can't figure out how to do it with a Book.where statement in ActiveRecord.
I think your best option is:
Book.where(keyword: words.split)
which will result in
SELECT * FROM books WHERE books.keyword IN ('new', 'science', 'fiction')
this will return the same records.
Note: Depending on your RDBMS IN() may be case sensitive. To avoid this we can change the above to
Book.where(Book.arel_table[:keyword].lower.in(words.downcase.split))
which will result in
SELECT * FROM books WHERE LOWER(books.keyword) IN ('new', 'science', 'fiction')
If you really want to go the with the way you have it now we can hack this together as follows:
Book.where(
Arel::Nodes::UnaryOperation.new(nil,Arel::Nodes.build_quoted(words))
.matches(
Arel::Nodes::NamedFunction.new(
'CONCAT',
[Arel.sql("'%'"),Book.arel_table[:keyword],Arel.sql("'%'")])
))
This will result in the desired SQL while still taking advantage of the escaping provided by Arel and the connection adapter.
Case sensitivity is not an issue here because Arel::Predications#matches uses case_sensitive = false by default meaning Postgres will use ILIKE instead of LIKE

Concatenation doesn't work in phpmyadmin XAMPP

I tried to use "||" for concatenation:
The query I used:
"SELECT id, name, age, age||id FROM myTable;"
This is the output:
Can anyone tell me why the output is not 201 (in first column) and 162(in second column)?? Also it gives similar outputs when I use two attributes that are of varchar datatype and the above two attributes are of int datatype.
Can anyone tell me why the output is not 201
its because, in mysql, you need to enable PIPES_AS_CONCAT. in order to work with ||
If the PIPES_AS_CONCAT SQL mode is enabled, || signifies the
SQL-standard string concatenation operator (like CONCAT()).
You can set it using phpmyadmin->variables->searchFor SQL_MODE
Refer mysql doc
But i would suggest you to use
CONCAT(columnName1, columnName2, ...)
There is no such concatenation in mySQL. This is Oracle SQL dialect. You have to use the CONCAT function in mysql
SELECT id, name, age, CONCAT(age,id) FROM myTable
visit the Mysql Documentations :
on this link you will find a list of String Functions and Operators
but you not use|| to concatenate caratcters or strings but do this :
SELECT id, name, age, concat(age,id) FROM myTable; or
SELECT id, name, age, concat_ws(' ',age,id) FROM myTable; if you want to space the age with id like this for example 23 1. 23 for age and 1 for id.

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

SQL Using the OR & AND operators (Newbie)

I am using the OR operator in the following fashion:
SELECT * FROM Customers
WHERE City = "Berlin" OR City = "London"
The above returns a results table containing some data, however what also returns data is:
SELECT * FROM Customers
Where City = "Berlin" OR "London"
I am using a questionable SQL editor currently, and want to know if this would be valid in a MySQL environment.
You are looking for
SELECT * FROM Customers Where City IN('Berlin', 'London');
The query:
Where City='Berlin' OR 'London'
Applies the logical OR operator (||), so OR "London" is equivalent to OR 0, and Where City = 'Berlin' OR 0; will just return 'Berlin'
SqlFiddle here with truth table here
Minor, but you should look at using single quotes for string literals, as this is more portable between RDBMS's and use of " will depend on ANSI QUOTES.
Well, Cassini i have check your syntax and run this query on my table i did not getting same result. I am getting correct output as expected.
i have run this command:
SELECT * FROM `city` where name = 'London' or 'Berlin'
and i got only london in name column. When i run this command:
SELECT * FROM `city` where name = 'London' or name = 'Berlin'
then i got both the cities in name column. so command is valid it will return only valid output which satisfy the condition.
So, i can say that command is valid but execute only that part of query which satisfy MYSQL Select syntax.
Well, if it valid in SQL, it should be valid in MySQL to. Are you wondering if this would be valid in MYSQL
SELECT * FROM Customers Where City="Berlin" OR"London"
It should be valid in MySQL
Hope that helps. If it does not, add a comment
this returnd the same values as your first sql-string.
But your first string is more readable for others.
You can use IN
SELECT *
FROM Customers
Where City IN ("Berlin","London")

Full JOIN MySQL Query is returning empty

So here is a MySQL Query:
SELECT TestSite . * , LoggedCarts . *
FROM TestSite, LoggedCarts
WHERE TestSite.email = 'LoggedCarts.Bill-Email'
LIMIT 0 , 30
It is returning an empty result set, when it should be returning four results based on the tables below.
First Table: LoggedCarts - Column: Bill-Email
casedilla#hotmail.com
crazyandy#theholeintheground.com
Second Table: TestSite - Column: email
samuel#lipsum.com
taco#flavoredkisses.com
honeybadger#dontcare.com
casedilla#hotmail.com
messingwith#sasquatch.com
The goal is to get a MySQL statement that returns the rows in Table: TestSite that don't match the rows in Table: LoggedCarts.
Note: I understand that the use of a hyphen in a column name requires special care when constructing a query, involving backticks to tell MySQL there are special characters. I would change the column names to match up, however the Table: LoggedCarts has data fed via post from a Yahoo Shopping Cart and without heavy preparation before insertion setting the name to anything but the key sent in the post data is daunting.
However, if it turns out rebuilding the data prior to insertion is easier than using a JOIN statement or for some reason using two columns with different names as the comparison columns just doesn't work, I will go through and rebuild the database and PHP code.
Single quotes indicate a string literal. You need to use backticks for identifiers. Also, each component of an identifier must be quoted individually.
SELECT TestSite . * , LoggedCarts . *
FROM TestSite, LoggedCarts
WHERE TestSite.email = LoggedCarts.`Bill-Email`
LIMIT 0 , 30
From the manual:
If any components of a multiple-part name require quoting, quote them individually rather than quoting the name as a whole. For example, write `my-table`.`my-column`, not `my-table.my-column`.
With a bit of research inspired by somne of the hints given, I found the solution I was looking for here: SELECT * WHERE NOT EXISTS
Does exactly what I need it to do, and as a bonus, I like the shorthand syntax that is used that allows you to put in an alias for the table name and use the alias throughout the statement.
SELECT *
FROM TestSite e
WHERE NOT EXISTS
(
SELECT null
FROM LoggedCarts d
WHERE d.`Bill-Email` = e.email
)