कॉलम में नकारात्मक मान रोकने के लिए INT UNSIGNED (या अन्य अनसाइन्ड पूर्णांक प्रकार) का उपयोग करें।
एक टेबल बनाते हैं:
CREATE TABLE preventNegativeNumberDemo (
UserId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
UserName VARCHAR(20),
UserGameScores INT
);
कॉलम को UNSIGNED में बदलें:
ALTER TABLE preventNegativeNumberDemo MODIFY COLUMN UserGameScores INT UNSIGNED NOT NULL;
विवरण जाँचें:
DESC preventNegativeNumberDemo;
आउटपुट
+----------------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------------+------------------+------+-----+---------+----------------+ | UserId | int(11) | NO | PRI | NULL | auto_increment | | UserName | varchar(20) | YES | | NULL | | | UserGameScores | int(10) unsigned | NO | | NULL | | +----------------+------------------+------+-----+---------+----------------+
नकारात्मक मान डालने का प्रयास:
INSERT INTO preventNegativeNumberDemo (UserName, UserGameScores) VALUES ('Larry', 0); -- OK
INSERT INTO preventNegativeNumberDemo (UserName, UserGameScores) VALUES ('Mike', -1); -- ERROR
INSERT INTO preventNegativeNumberDemo (UserName, UserGameScores) VALUES ('Sam', -100); -- ERROR
INSERT INTO preventNegativeNumberDemo (UserName, UserGameScores) VALUES ('John', 100); -- OK
INSERT INTO preventNegativeNumberDemo (UserName, UserGameScores) VALUES ('Bob', 200); -- OK
त्रुटि: ERROR 1264 (22003): Out of range value for column 'UserGameScores' at row 1
परिणाम देखें:
SELECT * FROM preventNegativeNumberDemo;
आउटपुट
+--------+----------+----------------+ | UserId | UserName | UserGameScores | +--------+----------+----------------+ | 1 | Larry | 0 | | 2 | John | 100 | | 3 | Bob | 200 | +--------+----------+----------------+
अनसाइन्ड पूर्णांक रेंज:
- TINYINT UNSIGNED: 0 - 255
- SMALLINT UNSIGNED: 0 - 65,535
- MEDIUMINT UNSIGNED: 0 - 16,777,215
- INT UNSIGNED: 0 - 4,294,967,295
- BIGINT UNSIGNED: 0 - 18,446,744,073,709,551,615