How do I make extra white space affect my MySQL query result? - mysql

I'm using MySQL 5.5.37. If I run the following query on my database
select count(*) FROM user where user_name = 'admin';
I get back the result "3". However, when I execute the query
select count(*) FROM user where user_name = 'admin ';
, (notice the extra spaces after the word "admin", I also get back the result "3". In fact, when i look at teh records, they are the same records as the first query. However, there are no records in my databaes with the user_name field equal to "admin ". Given that I cannot upgrade my MySQL database at this time, what can I do to ensure that the second query (wiht the extra white space) returns the correct result (i.e. "0")?
Edit: The user_name field is of type varchar(50).

I'm not 100% sure that it's the case, but it looks like your user_name field is a char(n) field and not varchar(n).
Such fields are filled with whitespaces to fully match the length of the field, while varchars are (I believe) null terminated strings.
Both queries return the same answer, as they also fill the missing characters with whitespaces.
If you want the query to work properly, consider changing the type of the column to varchar.

You could try using a regular expression as described in this post? Query for exact match of an string in SQL

select count(*) FROM [sb_user] where user_name = 'admin ';
you may try this one

Related

SQL - Query to find if a string contains part of the value in Column

I am trying to write a Query to find if a string contains part of the value in Column (Not to confuse with the query to find if a column contains part of a string).
Say for example I have a column in a table with values
ABC,XYZ
If I give search string
ABCDEFG
then I want the row with ABC to be displayed.
If my search string is XYZDSDS then the row with value XYZ should be displayed
The answer would be "use LIKE".
See the documentation: https://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html
You can do WHERE 'string' LIKE CONCAT(column , '%')
Thus the query becomes:
select * from t1 where 'ABCDEFG' LIKE CONCAT(column1,'%');
If you need to match anywhere in the string:
select * from t1 where 'ABCDEFG' LIKE CONCAT('%',column1,'%');
Here you can see it working in a fiddle:
http://sqlfiddle.com/#!9/d1596/4
Select * from table where #param like '%' + col + '%'
First, you appear to be storing lists of things in a column. This is the wrong approach to storing values in the database. You should have a junction table, with one row per entity and value -- that is, a separate row for ABC and XYZ in your example. SQL has a great data structure for storing lists. It is called a "table", not a "string".
If you are stuck with such a format and using MySQL, there is a function that can help:
where find_in_set('ABC', col)
MySQL treats a comma delimited string as a "set" and offers this function. However, this function cannot use indexes, so it is not particularly efficient. Did I mention that you should use a junction table instead?

How to search for substring in one of two fields of a table

I have a table with three columns: id, first, and last.
I'd like to find all records where 'SAM' is in either the first or last field.
I'm not an expert with MySQL, but it seems to me that one field could be queried using the LIKE operator.
How can I use LIKE in a query to get data from both columns at the same time?
I've tried this:
SELECT id
FROM `employees`
WHERE 'first' like 'SAM' OR 'last' like 'SAM'
But I get the message "You have an error in your SQL syntax; Check the manual that corresponds to your MySQL server version for the right syntax."
I can't seem to figure out why you are getting a syntax error, but one problem with your query is that by putting single quotes around your column name causes it to be treated like a string literal instead of a column name.
What I mean by that is instead of comparing the value in the first column with the string 'SAM', it's comparing two strings, 'first' and 'SAM' which are different. This query would return no results.
In addition, this will only work if the first or last name is equal to sam. To check for those characters as a substring at any point, I would add wildcards at the front and back of the strings.
Try this:
SELECT id
FROM employees
WHERE first LIKE '%SAM%' OR last LIKE '%SAM%'
Here is an SQL Fiddle to show how it works.
I don't see any syntax error in the query you posted. What you have is really close.
Your query isn't comparing the contents of the columns; it's comparing string literals, because of the single quotes, those are strings, not column references.
The LIKE comparison is equivalent to an equality comparison, since the there aren't any wildcard characters in the string on the right side. The '%' character is a wildcard that will match any number of characters.
To return rows where either of the columns first or last contain the string "SAM", you could do something like this:
SELECT e.id FROM employees e WHERE e.first LIKE '%SAM%' OR e.last LIKE '%SAM%'
That query would match any of these example rows:
id first last
-- --------- -------
2 Flotsam
3 Samson
5 Sesame
7 Yosemite Sam

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
)

MySQL Select Query - Get only first 10 characters of a value

Ok, so here is the issue.
I have a table with some columns and 'subject' is one of the columns.
I need to get the first 10 letters from the 'subject' field no matter the 'subject' field contains a string with 100 letters.
For example,
Table - tbl.
Columns - id, subject, value.
SQL Query:
SELECT subject FROM tbl WHERE id ='$id';
The result I am getting is, for example
Hello, this is my subject and how are you
I only require the first 10 characters
Hello, thi
I can understand that I can remove the rest of the characters using php substr() but that's not possible in my case. I need to get the excess characters removed by MySQL. How can this be done?
Using the below line
SELECT LEFT(subject , 10) FROM tbl
MySQL Doc.
SELECT SUBSTRING(subject, 1, 10) FROM tbl
Have a look at either Left or Substring if you need to chop it up even more.
Google and the MySQL docs are a good place to start - you'll usually not get such a warm response if you've not even tried to help yourself before asking a question.

MySQL query to prepend character to each entry

I have a table of users which has a username column consisting of a six digit number e.g 675381, I need to prepend a zero to each of these usernames e.g. 0675381 would be the final output of the previous example, is there a query that could handle this?
UPDATE Tablename SET Username = Concat('0', Username);
what type is the column of?
if it's string type, try something like this:
UPDATE your_table SET column_name=concat('0',column_name);
You mean "prepend" ? i.e. add it on the front?
Is the column numeric? Do you always want 7 characters output?
Assuming that, something like this would work for a query:
select LPAD(CONVERT(username, CHAR), 7, '0')
If the column is characters, the CONVERT() part is unnecessary, just LPAD the username.
If you want to permanently modify the value in the table, you'll need to ensure the column is a character type and UPDATE using the above.
You might want to use CONCAT_WS('', '0', Username) because if there is a null value, then you'll end up with NULL instead of '0'. This probably isn't a problem, but something I've learnt the hard way.