SUBSTRING और MID
In this page:
SUBSTRING(string, start_position, length)
MID(string, start_position, length)
Basic Substring
SUBSTRING position से किसी बड़ी string से text का एक छोटा टुकड़ा extract करता है, एक photo को सिर्फ ज़रूरी हिस्से तक crop करने जैसा। MySQL string positions को 1 से count करता है, 0 से नहीं, जो Python या JavaScript जैसी languages से आने वाले developers को confuse करता है।
उदाहरण: Basic Substring
SELECT SUBSTRING('Hello World', 1, 5) AS greeting;
MID Function इस्तेमाल करना
MID बस identical behavior और argument order के साथ SUBSTRING का एक alias है। MySQL इसे मुख्य रूप से दूसरे SQL dialects और उस नाम से लिखी गई पुरानी scripts के साथ compatibility के लिए रखता है, इसलिए आप जो भी आपको ज़्यादा natural लगे इस्तेमाल कर सकते हैं।
उदाहरण: Using the MID Function
SELECT MID('Hello World', 7, 5) AS target_word;
Negative Indexing
एक negative starting position pass करना MySQL को शुरुआत के बजाय string के अंत से backward count करने को कहता है। यह किसी value के आख़िरी कुछ characters पकड़ने का एक तेज़ तरीका है, जैसे पहले string की length calculate किए बिना एक card number के last 4 digits निकालना।
उदाहरण: Negative Indexing
CREATE TABLE cards (id INT, card_number TEXT);
INSERT INTO cards VALUES (1, '4111111111111234');
SELECT SUBSTRING(card_number, -4) AS last_four FROM cards;
एक Length Limit Set करना
एक तीसरा argument add करना यह cap कर देता है कि SUBSTRING कितने characters return करता है, इसलिए यह string के बिल्कुल अंत तक पढ़ने के बजाय रुक जाता है। एक start position को एक length के साथ combine करें एक exact fixed-width chunk निकालने के लिए, जैसे एक 2-character country code।
उदाहरण: Setting a Length Limit
CREATE TABLE countries (id INT, code_and_name TEXT);
INSERT INTO countries VALUES (1, 'INIndia');
SELECT SUBSTRING(code_and_name, 1, 2) AS country_code FROM countries;
Practical Use Cases
Real queries अक्सर unstructured text से structured pieces निकालने के लिए SUBSTRING को दूसरे string functions के साथ chain करती हैं, जैसे एक filename से एक year अलग करना या एक single column में stored email address से एक domain।
उदाहरण: Practical Use Cases
CREATE TABLE emails (id INT, email TEXT);
INSERT INTO emails VALUES (1, '[email protected]');
SELECT SUBSTRING(email, LOCATE('@', email) + 1) AS domain FROM emails;
- position
0से शुरू करना, जबकि MySQL string positions1से शुरू होते हैं। - तीसरे argument को एक end position समझ लेना, जबकि यह length है।
- यह भूल जाना कि
MIDबसSUBSTRINGके लिए एक alias है।
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: