शुरू करेंमुफ़्त में शुरू करें

विशिष्ट रिकॉर्ड्स डिलीट करना

where() क्लॉज़ का उपयोग करके, आप delete स्टेटमेंट को केवल कुछ खास रिकॉर्ड्स हटाने के लिए टार्गेट कर सकते हैं. उदाहरण के लिए, Jason ने employees टेबल से वे सभी रो डिलीट किए जिनका id 3 था, निम्न delete स्टेटमेंट के साथ:

delete(employees).where(employees.columns.id == 3) 

यहाँ आप वे सभी रो डिलीट करेंगे जिनके sex कॉलम में 'M' है और age कॉलम में 36 है. शुरुआत में हमने ऐसा कोड दिया है जो इन रो की कुल संख्या निकालता है. यह सुनिश्चित करना ज़रूरी है कि आप वास्तव में उतने ही रो डिलीट करें.

यह अभ्यास पाठ्यक्रम का हिस्सा है

Python में Databases का परिचय

पाठ्यक्रम देखें

अभ्यास निर्देश

  • census टेबल से डेटा हटाने के लिए एक delete स्टेटमेंट बनाइए. इसे delete_stmt के रूप में सेव करें.
  • delete_stmt में एक where क्लॉज़ जोड़िए जिसमें and_ हो ताकि वे रो फ़िल्टर हों जिनके sex कॉलम में 'M' है और age कॉलम में 36 है.
  • delete स्टेटमेंट को execute करें.
  • उत्तर सबमिट करें ताकि results के rowcount और to_delete दोनों प्रिंट हों, जहाँ to_delete वह संख्या देता है जितने रो डिलीट होने चाहिए. दोनों बराबर होने चाहिए — यह एक महत्वपूर्ण sanity check है!

इंटरैक्टिव व्यावहारिक अभ्यास

इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।

# Build a statement to count records using the sex column for Men ('M') age 36: count_stmt
count_stmt = select([func.count(census.columns.sex)]).where(
    and_(census.columns.sex == 'M',
         census.columns.age == 36)
)

# Execute the select statement and use the scalar() fetch method to save the record count
to_delete = connection.execute(count_stmt).scalar()

# Build a statement to delete records from the census table: delete_stmt
delete_stmt = ____

# Append a where clause to target Men ('M') age 36: delete_stmt
delete_stmt = delete_stmt.____(
    ____(census.columns.sex == ____,
         ____ == ____)
)

# Execute the statement: results
results = connection.execute(____)

# Print affected rowcount and to_delete record count, make sure they match
print(results.rowcount, to_delete)
कोड संपादित करें और चलाएँ