Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update statement causes fields to be updated with NULL or maximum value

If you had to pick one of the two following queries, which would you choose and why:

UPDATE `table1` AS e
SET e.points = e.points+(
SELECT points FROM `table2` AS ep WHERE e.cardnbr=ep.cardnbr);

or:

UPDATE `table1` AS e
INNER JOIN
(
   SELECT points, cardnbr
   FROM `table2`  
) AS ep ON (e.cardnbr=ep.cardnbr)
SET e.points = e.points+ep.points;

Tables' definitions:

CREATE TABLE `table1` (
  `cardnbr` int(10) DEFAULT NULL,
  `name` varchar(50) DEFAULT NULL,
  `points` decimal(7,3) DEFAULT '0.000',
  `email` varchar(50) NOT NULL DEFAULT '[email protected]',
  `id` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=25205 DEFAULT CHARSET=latin1$$

CREATE TABLE `table2` (
  `cardnbr` int(10) DEFAULT NULL,
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `points` decimal(7,3) DEFAULT '0.000',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci$$

UPDATE: BOTH are causing problems the first is causing non matched rows to update into NULL. The second is causing them to update into the max value 999.9999 (decimal 7,3). PS the cardnbr field is NOT a key

like image 202
coldShoulder Avatar asked Feb 05 '13 07:02

coldShoulder


People also ask

What does the UPDATE clause in an UPDATE statement do?

In SQL, the UPDATE statement is used to modify or update existing records in a table. You can use it to update everything all at once, or you can specify a subset of records to modify using the WHERE clause. The UPDATE statement is considered a SQL data manipulation command.

How do you UPDATE a column with null value?

UPDATE [table] SET [column]=0 WHERE [column] IS NULL; Null Values can be replaced in SQL by using UPDATE, SET, and WHERE to search a column in a table for nulls and replace them. In the example above it replaces them with 0. Cleaning data is important for analytics because messy data can lead to incorrect analysis.

Which statement is used to UPDATE?

The UPDATE statement is used to modify the existing records in a table.

How do I UPDATE a field to null in Oracle?

Click in the column value you want to set to (null) . Select the value and delete it. Hit the commit button (green check-mark button). It should now be null.


1 Answers

I prefer the second one..reason for that is

When using JOIN the databse can create an execution plan that is better for your query and save time whereas subqueries (like your first one ) will run all the queries and load all the datas which may take time.

i think subqueries is easy to read but performance wise JOIN is faster...

like image 122
bipen Avatar answered Sep 28 '22 04:09

bipen