![]() |
|
|
#1 |
|
Senior Member
Join Date: Aug 2011
Posts: 111
|
When creating an integer data type, define it as unsigned if the column is never going to store negative values. This prevents unwanted negative numbers from being stored in the column. In addition, unsigned integer is smaller in length than the corresponding signed integer. For example, auto-incremented (starting from 1) primary key column is a good candidate for unsigned int.
E.g. OrderID is defined as unsigned integer because we know it does not make sense if OrderID is a negative number. However, there is one problem with unsigned integer when we apply mathematical operation (subtraction). Here is the illustration: 1. Create a table called example with unsigned integers CREATE TABLE `example` ( `test` int(10) unsigned NOT NULL default '0', `test2` mediumint(8) unsigned NOT NULL default '0', `test3` smallint(5) unsigned NOT NULL default '0', `test4` tinyint(3) unsigned NOT NULL default '0' ) 2. Then we add one record to the 'example' table. Add integer 5 for all 4 columns. insert into `example`(`test`,`test2`,`test3`,`test4`) values (5,5,5,5); Code:
<PRE> ------------------------------------------------------------------------ test test2 test3 test4 ------------------------------------------------------------------------ 5 5 5 5 </PRE> update example set test = test - 6 update example set test2 = test2 - 6 update example set test3 = test3 - 6 update example set test4 = test4 - 6 4. Check what the value is in each column after the updates. Code:
<PRE> ----------------------------------------------------------------------------- test test2 test3 test4 ------------------------------------------------------------------------------ 4294967295 16777215 65535 255 </PRE> To fixed the problem, MySQL recommends the use of CAST function - CAST(expr AS type). It will cast the value to 0 if a negative value is returned. update example set test = CAST(test - 6 AS SIGNED) update example set test2 = CAST(test2 - 6 AS SIGNED) update example set test3 = CAST(test3 - 6 AS SIGNED) update example set test4 = CAST(test4 - 6 AS SIGNED) After updation the result will look like this, Code:
<PRE> ------------------------------------- --------------------- test test2 test3 test4 -------------------------------------- -------------------- 0 0 0 0 </PRE> Thank you for reading. Please don't hesitate to drop your valuable comments as it helps improving this thread. Last edited by kaman; 20-08-2011 at 01:01 PM. |
|
|
|
|
|
#2 |
|
Senior Member
Join Date: Aug 2011
Posts: 110
|
nice information
thanx |
|
|
|
|
|
#3 |
|
Senior Member
Join Date: Aug 2011
Posts: 111
|
Thank you Mr Sharma for your prompt response.
|
|
|
|
|
|
#4 |
|
Senior Member
Join Date: Aug 2011
Posts: 103
|
yes this is good sharing we are also adopting this funda
|
|
|
|
![]() |
| Tags |
| mysql unsigned integer, unsigned integer tips, using unsigned integer |
| Thread Tools | |
| Display Modes | |
|
|