Why * is Inserted in SQL - sql-server-2008

This happened when I was just testing.
I've created a table as
Create Table Test_Table
(
Field_char char(1)
);
When I want to insert value with code
Insert Into Test_Table(Field_char)
Select 13;
It inserts '*' in the column. For single digits it inserts them as it is. If the length is modified from 1 to 2, similar thing happen for 3 digits input such as 100 etc.
Why is this?

In your create statement you set the length of Field_char to 1 (char(1)). This means that your entries must have a length smaller or equal to 1. valid entries are 1,2 etc. Invalid entries are 12, 13 as they are longer than 1 char -> * is a placeholder to indicate invalid values.
EDIT: (Thanks To Vladimir)
To be more precise take a look here.
Truncating and Rounding Results
[...] Conversions to char, varchar, nchar, nvarchar, binary, and varbinary are truncated, except for the conversions shown in the following table.
There we have the following entry:
From data type int to data type char result *
where * = Result length too short to display

When you are writing
Insert Into Test_Table(Field_char)
Select 13;
The it is converting int to char. So your 13 is converted into *. If you want you can check by writing
select CONVERT(char(1),13)
If you want to see the result as 13 then you need to put that in single inverted comma like this:
Insert Into Test_Table(Field_char)
Select '13';
And also you need to increase the size of column as char(1) can hold only one character.
SQL FIDDLE DEMO

It simply Convert Int to Char
for Example
select CONVERT(char(1),13)
it will give *
Sql Implicitly convert int to char which is you column type..

Related

MYSQL, Insert the numeric characters of a string in a column to another column

I am trying to clean the telephone numbers of a database so we can easily search for them. In the column TEL we have rows like:
654-598-5487
654.254.2456
(458)-5458789 e.3
I want to copy all those values to a new column where only the numeric characters are transferred:
6545985487
6542542456
45854587893
The new column (TEL_NO_FORMAT) is a big int and it only allows numbers, but if I execute something like this:
UPDATE CLIENTS set `TEL_NO_FORMAT` = `TEL`
It will only transfer the first numeric characters found and ignore the rest:
654
654
NULL
Easiest way is the REGEXP_REPLACE(MySQL 8.0+):
SELECT *, REGEXP_REPLACE(tel_no_format, '[^0-9]','') AS result
FROM clients
Answering the question in an update query
UPDATE CLIENTS SET TEL_NO_FORMAT = REGEXP_REPLACE(TEL, '[^0-9]','');
You should replace the undesired char before
UPDATE CLIENTS set `TEL_NO_FORMAT` = replace(replace(replace(`TEL`, '.',''),'-',''),')','')
because some char (eg '-') are create problem during conversion ..
anyway rember that a big int can't manage properly eventual tel number 0 prefixed eg:
00453778988

MySQL update query to prepend digit to existing column with integers values

I have a mysql database column named like telephoneNo
Telephone No
25645656
45454545
45565656
I want to prepend two digits XX to every value of telephoneNo column
Telephone No
xx25645656
xx45454545
xx45565656
I was trying to workout with concat but its not with integer values in my case please help with update query
You can use CAST() to convert your integers explicitely:
UPDATE t SET phone=CAST(CONCAT('10', phone) AS UNSIGNED)
That will work with integer prefixes. However, I don't see solid reason to store phone numbers as integers and not strings
That's a hack change your col to varchar or something.
UPDATE table SET telephoneNo=9200000000+telephoneNo;
EDIT:
This method requires that all your numbers are of the same length, and 8 digits long, if all your numbers are more or less than 8 digits modify the number of 0's after the 92 accordingly
If your telephone column is int, you can use concat string function to concat with int or string even like below
SELECT CONCAT(xx, telephone);
(OR)
SELECT CONCAT('xx', telephone);
(OR)
Explicitly cast your int column value
SELECT CONCAT('xx', CAST(telephone AS CHAR));

Data truncated for column?

After changing the data type of a MySql column in order to store Twilio call ids (34 char strings), I try to manually change the data in that column with:
update calls
set incoming_Cid='CA9321a83241035b4c3d3e7a4f7aa6970d'
where id='1';
However I get an error which doesn't make sense seeing as the column's data type was properly modified?
| Level ||| Code | Message
| Warning | 1265 | Data truncated for column 'incoming_Cid' at row 1
Your problem is that at the moment your incoming_Cid column defined as CHAR(1) when it should be CHAR(34).
To fix this just issue this command to change your columns' length from 1 to 34
ALTER TABLE calls CHANGE incoming_Cid incoming_Cid CHAR(34);
Here is SQLFiddle demo
I had the same problem because of an table column which was defined as ENUM('x','y','z') and later on I was trying to save the value 'a' into this column, thus I got the mentioned error.
Solved by altering the table column definition and added value 'a' into the enum set.
By issuing this statement:
ALTER TABLES call MODIFY incoming_Cid CHAR;
... you omitted the length parameter. Your query was therefore equivalent to:
ALTER TABLE calls MODIFY incoming_Cid CHAR(1);
You must specify the field size for sizes larger than 1:
ALTER TABLE calls MODIFY incoming_Cid CHAR(34);
However I get an error which doesn't make sense seeing as the column's data type was properly modified?
| Level | Code | Msg | Warn | 12 | Data truncated for column 'incoming_Cid' at row 1
You can often get this message when you are doing something like the following:
REPLACE INTO table2 (SELECT * FROM table1);
Resulted in our case in the following error:
SQL Exception: Data truncated for column 'level' at row 1
The problem turned out to be column misalignment that resulted in a tinyint trying to be stored in a datetime field or vice versa.
In my case it was a table with an ENUM that accepts the days of the week as integers (0 to 6). When inserting the value 0 as an integer I got the error message "Data truncated for column ..." so to fix it I had to cast the integer to a string. So instead of:
$item->day = 0;
I had to do;
$item->day = (string) 0;
It looks silly to cast the zero like that but in my case it was in a Laravel factory, and I had to write it like this:
$factory->define(App\Schedule::class, function (Faker $faker) {
return [
'day' => (string) $faker->numberBetween(0, 6),
//
];
});
I had the same problem, with a database field with type "SET" which is an enum type.
I tried to add a value which was not in that list.
The value I tried to add had the decimal value 256, but the enum list only had 8 values.
1: 1 -> A
2: 2 -> B
3: 4 -> C
4: 8 -> D
5: 16 -> E
6: 32 -> F
7: 64 -> G
8: 128 -> H
So I just had to add the additional value to the field.
Reading this documentation entry helped me to understand the problem.
MySQL stores SET values numerically, with the low-order bit of the
stored value corresponding to the first set member. If you retrieve a
SET value in a numeric context, the value retrieved has bits set
corresponding to the set members that make up the column value. For
example, you can retrieve numeric values from a SET column like this:
mysql> SELECT set_col+0 FROM tbl_name; If a number is stored into a
If a number is stored into a SET column, the bits that are set in the
binary representation of the number determine the set members in the
column value. For a column specified as SET('a','b','c','d'), the
members have the following decimal and binary values.
SET Member Decimal Value Binary Value
'a' 1 0001
'b' 2 0010
'c' 4 0100
'd' 8 1000
If you assign a value of 9 to this column, that is 1001 in binary, so
the first and fourth SET value members 'a' and 'd' are selected and
the resulting value is 'a,d'.
when i first tried to import csv into mysql , i got the same error , and then i figured out mysql table i created doesn't have the character length of the importing csv field ,
so if it's the first time importing csv
its a good idea to give more character length .
label all fields as varchar or text , don't blend int or other values.
then you are good to go.
Check whether you are using the 'enum' datatype.If you are using 'enum' datatype then the items inside the enum datatype should be exactly match with the data which you are entering.Ex.
You are taking the enum datatype like this:
enum('book',stationery','others')
then when you are inserting the data into the database you have to do like this:
INSERT INTO database_name.table_name (column1,...columnn) VALUES().
THE value should include same items which you are mentioned within the bracket of enum datatype.
my issue was I used single quote instead of double quotes which add extra words in Boolean column
I Faced the same issue .In my case i was inserting a empty string for a numeric column.But by inserting a numeric value in string form for same column it got resolved e.g '12.56' --> numeric column will work but '' --> numeric column will give the above mentioned error.
Note: For numeric columns in MySql we can pass values in double quotes also .
In some cases this can be result of wrong type of input. For example, you have a column decimal(10,2) and the input isn't sanitized and is 7,7 but should be 7.7.

Querying a string from int column?

I have a table:
CREATE TABLE `ids` (
id int(11) not null auto_increment,
PRIMARY KEY (id)
);
It contains some IDs: 111, 112, 113, 114 etc.
I made a query:
SELECT * FROM `ids` WHERE id = '112abcdefg'
I expected nothing but I've got a result, a row with ID of 112. Seems that MySQL quietly converted my string to integer and then compared it against column values.
How can I change the query so that querying the same string from id column will give no results as I expect? Is there a strict comparison modifier in MySQL?
One option is to CAST the 112 to CHAR to get a proper match:
WHERE CAST(id AS CHAR(12)) = '112abcdefg'
The 12 in CHAR is a guess; it should be large enough for your biggest id.
That will probably kill any chance of optimization, so another option (though one I'm not 100% sure of) is to use a BINARY comparison. I've tried this with a few different values and it works:
WHERE BINARY id = '112abcdefg'
You are comparing a string, just put the number with no quotes:
SELECT * FROM `ids` WHERE id = 112
If you dont, it will convert the string '112abcdefg' to a number and say its 112
The response you are seeing is because you are trying to compare an integer column to a string value. In that case, MySQL will type-cast the string literal value to an integer, and when it does that it starts from the left of the string and as soon as it reaches a character that cannot be considered part of a number, it strips out everything from that point on. So trying to compare "256abcd" to an integer column will result in actually comparing the number 256.
So your options (or at least a few of them) would be:
Validate the input string in your application code and reject it if it's not an integer (see the ctype_digit function in PHP).
Change the column type for the filename if you want to treat it as a string (e.g. a VARCHAR type).
Cast the column value to a string:
. . . WHERE CAST(Id AS CHAR) = '256aei'
Source
you can use this :
SET sql_mode = STRICT_TRANS_TABLES;
this sets you sql mode to strict checking, and then try firing the query you mentioned.
lame + kills optimization but serves it purpose
SELECT * FROM `ids` WHERE concat(id) = '112abcdefg';
that way you enforce casting to string
http://dev.mysql.com/doc/refman/5.1/en/type-conversion.html

Defining length of CHAR type in Mysql

Consider the two String types in MySQL
1.Char[LENGTH]
2.Varchar[LENGTH]
Question:Defining the LENGTH field is necessary For which type Varchar or Char ?
According to My opinion It is Char but In one tutorial it is written that you must define Length for Varchar while there is no such requirement for Char type.
CHAR(M) - A fixed-length string between 1 and 255 characters in length (for example
CHAR(5)), right-padded with spaces to the specified length when stored. Defining a length
is not required, but the default is 1.
VARCHAR(M) - A variable-length string between 1 and 255 characters in length; for
example VARCHAR(25). You must define a length when creating a VARCHAR field.
Link: www.tutorialspoint.com/mysql/mysql-data-types.htm
Is the thing Written in Tutorial Right?
If I'm clear with what you are looking for .
Take a look at this.
CREATE TABLE mytable (column1 VARCHAR(20), column2 CHAR);
insert into mytable values('stackoverflow','v');
select * from mytable;
If you don't specify the length for char datatype it will take 1 as default.
Now if you try to insert string in column2 more than length 1 it will raise an error.
Summary : Varchar datatype need length otherwise it will raise an error where in char datatype if you don't specify the length it will take 1 as default.