استعلامات الاسترجاع الأساسية وتحديث البيانات في SQL
تغطي هذه الوحدة استعلامات الاسترجاع الأساسية في SQL، الفرق بين المجموعات (Sets) والحقائب (Bags)، عمليات الدمج، مطابقة الأنماط، بالإضافة إلى أوامر الإدراج والحذف والتحديث.
Basic Retrieval Queries and Update Statements in SQL
This module covers basic SQL retrieval queries, the difference between Sets and Bags, set operations, pattern matching, and INSERT, DELETE, and UPDATE statements.
أهداف التعلم
- كتابة استعلامات SQL لاسترجاع السجلات من قاعدة البيانات.
- كتابة استعلامات SQL لإدراج سجلات جديدة في الجداول.
- كتابة استعلامات SQL لحذف السجلات وتحديثها بشكل آمن.
- Write SQL queries for retrieval of records.
- Write SQL queries for inserting records.
- Write SQL queries for deleting and updating records.
1 جملة الاسترجاع الأساسية (SELECT)
1 Basic Retrieval Queries (SELECT)
اللبنة الأساسية في SQL لاستخراج البيانات، وتتكون من تحديد الأعمدة (SELECT)، الجداول (FROM)، والشروط (WHERE).
The core SQL statement for retrieving information, consisting of SELECT, FROM, and WHERE clauses.
أبسط شكل لجملة SELECT في SQL يُسمى كتلة (SELECT-FROM-WHERE).
تحدد قائمة الأعمدة (attribute list) في SELECT البيانات المراد استرجاعها. تحدد قائمة الجداول (table list) في FROM الجداول المطلوبة. ويحدد الشرط (condition) في WHERE التعبيرات المنطقية التي يجب أن تستوفيها السجلات (tuples) ليتم استرجاعها.
يمكن أن يحتوي الشرط على شروط اختيار (selection conditions) لجدول واحد، أو شروط ربط (join conditions) لربط سجلات من جداول متعددة.
The simplest form of the SQL SELECT statement is called a mapping or a SELECT-FROM-WHERE block.
The SELECT clause specifies the attribute list to retrieve. The FROM clause specifies the table list required. The WHERE clause specifies the Boolean condition that identifies the tuples to be retrieved.
Conditions can be selection conditions (filtering a single table) or join conditions (combining records from multiple tables).
ترتيب التنفيذ الفعلي في محرك قاعدة البيانات يختلف عن ترتيب الكتابة؛ حيث يتم تقييم FROM أولاً لتحديد المصادر، ثم WHERE لتصفية السجلات، وأخيراً SELECT لتحديد الأعمدة المطلوبة.
هذا يفسر لماذا لا يمكن استخدام الأسماء المستعارة المحددة في SELECT داخل جملة WHERE.
The logical execution order differs from the written order: FROM is evaluated first, then WHERE, and finally SELECT.
This explains why aliases defined in the SELECT clause cannot be used in the WHERE clause.
SELECT FNAME, LNAME, ADDRESS FROM EMPLOYEE, DEPARTMENT WHERE DNAME='Research' AND DNUMBER=DNO;
لماذا نعتبر جملة SELECT في SQL مختلفة عن عملية SELECT في الجبر العلائقي؟ Why is the SQL SELECT statement considered different from the SELECT operation in relational algebra?
في الجبر العلائقي، عملية SELECT (سيجما) تقوم بتصفية الصفوف فقط (مثل WHERE في SQL)، بينما عملية PROJECT (باي) تحدد الأعمدة. جملة SELECT في SQL تدمج كلا العمليتين معاً.
In relational algebra, SELECT (sigma) filters rows (like SQL's WHERE), and PROJECT (pi) selects columns. SQL's SELECT statement combines both operations.
2 الحقائب (Multisets) مقابل المجموعات (Sets)
2 Bags (Multisets) versus Sets
في SQL، الجداول هي حقائب (Bags) تسمح بتكرار السجلات، وليست مجموعات رياضية صارمة (Sets) تمنع التكرار.
In SQL, tables are bags (multisets) that allow duplicate tuples, unlike strict mathematical sets which do not.
يوجد تمييز مهم بين نموذج SQL العملي والنموذج العلائقي الرسمي.
يسمح SQL للجدول (العلاقة) باحتواء سجلين أو أكثر متطابقين في جميع قيم السمات. لذلك، علاقة SQL هي حقيبة (Bag أو Multiset) وليست مجموعة (Set).
الحقيبة تشبه المجموعة ولكن يمكن أن يظهر العنصر أكثر من مرة، والترتيب فيها غير مهم.
يمكن إجبار علاقات SQL لتكون مجموعات عن طريق تحديد PRIMARY KEY أو UNIQUE، أو باستخدام الكلمة المفتاحية DISTINCT في الاستعلام.
There is an important distinction between the practical SQL model and the formal relational model.
SQL allows a table to have two or more tuples that are identical in all their attribute values. Hence, an SQL relation is a multi-set (bag) of tuples, not a set.
A bag is like a set, but an element may appear more than once (order is irrelevant).
SQL relations can be constrained to be sets by specifying PRIMARY KEY or UNIQUE attributes, or by using the DISTINCT option in a query.
تم تصميم SQL للعمل بالحقائب بدلاً من المجموعات لأسباب تتعلق بالأداء.
إزالة التكرارات (لتحويل النتيجة إلى مجموعة) تتطلب عملية فرز (Sorting) مكلفة جداً من حيث الموارد.
لذلك، يترك SQL قرار إزالة التكرارات للمبرمج باستخدام DISTINCT فقط عند الحاجة.
SQL was designed to use bags instead of sets for performance reasons.
Eliminating duplicates (to enforce set semantics) requires sorting the result, which is computationally expensive.
SQL leaves the choice to the developer to use DISTINCT only when necessary.
SELECT SALARY FROM EMPLOYEE; -- Returns a Bag (duplicates allowed)
SELECT DISTINCT SALARY FROM EMPLOYEE; -- Returns a Set (no duplicates)
| Sets (المجموعات) | Bags / Multisets (الحقائب) | |
|---|---|---|
| التكرارDuplicates | غير مسموحNot allowed | مسموحAllowed |
| النموذج المستخدمModel Used In | النموذج العلائقي الرسميFormal Relational Model | نموذج SQL العمليPractical SQL Model |
| الأداء (بدون فهارس)Performance (Unindexed) | بطيء (يتطلب فرز لإزالة التكرار)Slow (requires sorting to remove duplicates) | سريعFast |
هل {A, B, A} تساوي {B, A, A} كحقائب؟ وهل تساوي [A, B, A] كقوائم؟ Does {A, B, A} equal {B, A, A} as bags? Does it equal [A, B, A] as lists?
نعم، متساويتان كحقائب لأن الترتيب غير مهم. لكن كقوائم (Lists)، [A, B, A] لا تساوي [B, A, A] لأن الترتيب مهم في القوائم.
Yes, they are equal as bags because order is irrelevant. However, as lists, [A, B, A] is not equal to [B, A, A] because order matters in lists.
3 الأسماء المستعارة وتأهيل السمات
3 Aliasing and Qualifying Attributes
استخدام اسم الجدول أو اسم مستعار (Alias) قبل اسم العمود لمنع الغموض، خاصة عند استخدام نفس اسم العمود في جداول مختلفة أو عند ربط الجدول بنفسه.
Prefixing attribute names with table names or aliases to resolve ambiguity, especially in self-joins or when tables share column names.
في SQL، يجب أن تكون جميع أسماء السمات في جدول معين مختلفة، ولكن يمكن استخدام نفس الاسم في جداول مختلفة.
في هذه الحالة، يجب تأهيل (Qualify) اسم السمة باستخدام اسم الجدول (مثل EMPLOYEE.LNAME).
لتبسيط الاستعلامات، يمكن استخدام الأسماء المستعارة (Aliases أو Tuple Variables) باستخدام الكلمة المفتاحية AS.
تعتبر الأسماء المستعارة ضرورية جداً عندما يحتاج الاستعلام إلى الإشارة لنفس الجدول مرتين (Self-Join)، حيث تعمل الأسماء المستعارة كنسخ مختلفة من نفس الجدول.
In SQL, attribute names within a table must be unique, but the same name can be used across different tables.
When this happens, attributes must be qualified with the table name (e.g., EMPLOYEE.LNAME).
To simplify, aliases (tuple variables) can be used via the AS keyword.
Aliases are strictly required when a query refers to the same relation twice (a self-join), acting as different copies of the table (e.g., one for supervisors, one for subordinates).
الأسماء المستعارة (Tuple Variables) ترتبط بمفهوم حساب التفاضل والتكامل العلائقي (Relational Calculus)، حيث يمثل المتغير صفاً (Tuple) يمر عبر جميع صفوف الجدول لتقييم الشروط.
Tuple variables (aliases) stem from Tuple Relational Calculus, where the variable iterates over all tuples in the relation to evaluate the query predicate.
SELECT E.FNAME, S.FNAME FROM EMPLOYEE AS E, EMPLOYEE AS S WHERE E.SUPERSSN = S.SSN;
ماذا يحدث إذا قمنا بربط جدول EMPLOYEE بنفسه دون استخدام الأسماء المستعارة؟ What happens if we join the EMPLOYEE table to itself without using aliases?
سيرفض محرك قاعدة البيانات الاستعلام بسبب الغموض (Ambiguity)، حيث لن يتمكن من التمييز بين النسختين من نفس الجدول عند الإشارة إلى الأعمدة.
The database engine will reject the query due to ambiguity, as it cannot distinguish between the two instances of the table when referencing columns.
4 غياب شرط WHERE (الضرب الديكارتي)
4 Missing WHERE-clause (Cartesian Product)
نسيان جملة WHERE عند الاستعلام من جداول متعددة يؤدي إلى دمج كل صف من الجدول الأول مع كل صف من الجدول الثاني (الضرب الديكارتي).
Omitting the WHERE clause when querying multiple tables joins every row of the first table with every row of the second (Cartesian Product).
جملة WHERE اختيارية في SQL. إذا كانت مفقودة، فهذا يعني عدم وجود شروط (يكافئ WHERE TRUE)، ويتم تحديد جميع السجلات.
إذا تم تحديد أكثر من جدول في جملة FROM ولم يكن هناك شرط WHERE (أي لا توجد شروط ربط)، فسيتم دمج جميع المجموعات الممكنة من السجلات معاً. يُعرف هذا بالضرب الديكارتي (Cartesian Product).
من المهم جداً عدم إغفال شروط الربط لتجنب نتائج استعلام غير صحيحة وضخمة جداً.
The WHERE clause is optional. A missing WHERE clause indicates no condition (equivalent to WHERE TRUE), selecting all tuples.
If multiple relations are specified in the FROM clause without a WHERE clause (no join conditions), all possible combinations of tuples are joined together. This is known as the CARTESIAN PRODUCT.
It is extremely important not to overlook join conditions to avoid incorrect and massive query results.
الضرب الديكارتي ينمو بشكل أسي. إذا كان الجدول الأول يحتوي على 1000 صف والثاني 1000 صف، فإن النتيجة ستكون مليون صف.
هذا يمكن أن يؤدي إلى استنفاد ذاكرة الخادم (OOM) أو إبطاء الشبكة بشكل كبير.
Cartesian products grow exponentially. If table A has 1,000 rows and table B has 1,000 rows, the result is 1,000,000 rows.
This can lead to Out-Of-Memory (OOM) errors or severe network congestion.
SELECT SSN, DNAME FROM EMPLOYEE, DEPARTMENT; -- DANGER: Cartesian Product
متى يكون الضرب الديكارتي مقصوداً ومفيداً في قواعد البيانات؟ When is a Cartesian Product intentional and useful in databases?
نادر جداً، ولكن قد يُستخدم لإنشاء بيانات اختبارية ضخمة، أو لإنشاء جدول يمثل جميع التوافيق الممكنة (مثل جميع الألوان مع جميع الأحجام لمنتج معين).
Very rarely, but it can be used to generate massive test data, or to create a matrix of all possible combinations (e.g., all colors matched with all sizes for a product).
5 عمليات المجموعات والحقائب
5 Set and Multiset Operations in SQL
عمليات تدمج نتائج استعلامين: UNION (اتحاد)، INTERSECT (تقاطع)، EXCEPT (فرق). الإصدارات العادية تزيل التكرار، وإصدارات ALL تحتفظ به.
Operations combining two query results: UNION, INTERSECT, EXCEPT. Standard versions remove duplicates; ALL versions keep them.
يدمج SQL عمليات المجموعات مباشرة: UNION، EXCEPT (أو MINUS)، و INTERSECT.
نتائج هذه العمليات هي مجموعات (Sets) من السجلات، حيث يتم إزالة التكرارات تلقائياً.
يجب أن تكون الجداول متوافقة نوعياً (Type Compatible أو Union Compatible)، أي لها نفس أنواع السمات وبنفس الترتيب.
إذا أراد المستخدم الاحتفاظ بالتكرارات (التعامل كحقائب)، يمكنه استخدام عمليات الحقائب: UNION ALL، EXCEPT ALL، و INTERSECT ALL.
SQL incorporates set operations: UNION, EXCEPT (or MINUS), and INTERSECT.
The results of these operations are sets of tuples; duplicate tuples are eliminated.
The operations apply only to type-compatible (union-compatible) relations, meaning they must have the same attribute types in the same order.
If duplicates are desired, SQL provides multiset operations: UNION ALL, EXCEPT ALL, and INTERSECT ALL.
استخدام UNION ALL أسرع بكثير من UNION لأنه لا يتطلب خطوة الفرز (Sorting) لإزالة التكرارات.
كقاعدة عامة في تحسين الأداء، استخدم UNION ALL دائماً إلا إذا كنت متأكداً من حاجتك لإزالة التكرارات.
UNION ALL is significantly faster than UNION because it skips the sorting step required for duplicate elimination.
As a performance best practice, always use UNION ALL unless duplicate removal is strictly necessary.
(SELECT PNAME FROM PROJECT, DEPARTMENT, EMPLOYEE WHERE DNUM=DNUMBER AND MGRSSN=SSN AND LNAME='Smith') UNION (SELECT PNAME FROM PROJECT, WORKS_ON, EMPLOYEE WHERE PNUMBER=PNO AND ESSN=SSN AND LNAME='Smith');
| Set Operations (UNION, INTERSECT) | Multiset Operations (UNION ALL, INTERSECT ALL) | |
|---|---|---|
| التعامل مع التكرارHandling Duplicates | يتم إزالة التكراراتDuplicates are eliminated | يتم الاحتفاظ بالتكراراتDuplicates are retained |
إذا كان الاستعلام الأول يرجع 5 صفوف، والثاني يرجع 3 صفوف (منها صفان مكرران مع الأول). كم عدد الصفوف الناتجة عن UNION و UNION ALL؟ If query A returns 5 rows, and query B returns 3 rows (2 of which are duplicates of A). How many rows result from UNION and UNION ALL?
UNION سيرجع 6 صفوف (5 + 3 - 2 مكرر). UNION ALL سيرجع 8 صفوف (5 + 3).
UNION returns 6 rows (5 + 3 - 2 duplicates). UNION ALL returns 8 rows (5 + 3).
6 مقارنة السلاسل النصية (LIKE)
6 Substring Comparison Conditions (LIKE)
استخدام المعامل LIKE للبحث عن نصوص جزئية باستخدام الرموز `%` (لأي عدد من الحروف) و `_` (لحرف واحد فقط).
Using the LIKE operator to search for partial strings with wildcards `%` (any number of characters) and `_` (exactly one character).
يُستخدم معامل المقارنة LIKE لمقارنة السلاسل النصية الجزئية.
يتم استخدام حرفين محجوزين (Wildcards): الرمز `%` (أو `*` في بعض الأنظمة) يحل محل عدد عشوائي من الحروف (صفر أو أكثر)، والرمز `_` يحل محل حرف عشوائي واحد فقط.
يسمح هذا المعامل للمستخدمين بتجاوز حقيقة أن كل قيمة في SQL تعتبر ذرية (Atomic) وغير قابلة للتجزئة، مما يتيح البحث داخل النصوص.
The LIKE comparison operator is used to compare partial strings.
Two reserved characters are used: '%' (or '*' in some implementations) replaces an arbitrary number of characters, and '_' replaces a single arbitrary character.
The LIKE operator allows users to get around the fact that each value is considered atomic and indivisible in SQL, enabling substring searches.
استخدام `%` في بداية النمط (مثل `'%Smith'`) يمنع قاعدة البيانات من استخدام الفهارس (Indexes) العادية، مما يؤدي إلى فحص الجدول بالكامل (Full Table Scan) وبطء الاستعلام.
يفضل دائماً تجنب الـ Wildcard في البداية إذا أمكن.
Using a leading wildcard (e.g., `'%Smith'`) prevents the database from using standard B-Tree indexes, resulting in a Full Table Scan and poor performance.
It is best practice to avoid leading wildcards when possible.
SELECT FNAME FROM EMPLOYEE WHERE ADDRESS LIKE '%Houston,TX%';
SELECT FNAME FROM EMPLOYEE WHERE BDATE LIKE '__5_______';
كيف تبحث عن نص يحتوي فعلياً على الرمز `%` أو `_` دون أن يعتبره SQL حرف بدل؟ How do you search for a string that actually contains the '%' or '_' character without SQL treating it as a wildcard?
باستخدام كلمة ESCAPE لتحديد حرف هروب، مثل: `LIKE '%100!%%' ESCAPE '!'` للبحث عن '100%'.
By using the ESCAPE clause to define an escape character, e.g., `LIKE '%100!%%' ESCAPE '!'` to search for '100%'.
7 ترتيب النتائج (ORDER BY)
7 Ordering Query Results (ORDER BY)
تُستخدم جملة ORDER BY لفرز النتائج تصاعدياً (ASC) أو تنازلياً (DESC) بناءً على عمود واحد أو أكثر.
The ORDER BY clause sorts the query results in ascending (ASC) or descending (DESC) order based on one or more attributes.
تُستخدم جملة ORDER BY لفرز السجلات في نتيجة الاستعلام بناءً على قيم سمة (أو سمات) معينة.
الترتيب الافتراضي هو الترتيب التصاعدي (ASC). يمكننا تحديد الكلمة المفتاحية DESC إذا أردنا ترتيباً تنازلياً.
بدون ORDER BY، تظهر الصفوف في نتيجة الاستعلام بترتيب عشوائي يحدده النظام.
يمكن الترتيب بناءً على أعمدة متعددة، حيث يتم الفرز بالعمود الأول، ثم الثاني في حال التساوي.
The ORDER BY clause is used to sort the tuples in a query result based on the values of some attribute(s).
The default order is ascending (ASC). We can specify the keyword DESC for descending order.
Without ORDER BY, the rows in a query result appear in some system-determined (random) order.
Sorting can be applied to multiple columns sequentially.
عملية الفرز (Sorting) مكلفة جداً وتستهلك الذاكرة ووقت المعالج.
تعتمد قواعد البيانات بشكل كبير على الفهارس (Indexes) لتسريع عمليات ORDER BY دون الحاجة لفرز البيانات فعلياً في الذاكرة.
Sorting is an expensive operation consuming CPU and memory.
Databases heavily rely on Indexes to optimize ORDER BY clauses, allowing them to retrieve data pre-sorted without performing an actual in-memory sort.
SELECT DNAME, LNAME FROM DEPARTMENT, EMPLOYEE ORDER BY DNAME ASC, LNAME DESC;
هل يمكن استخدام ORDER BY لترتيب النتائج بناءً على عمود غير موجود في جملة SELECT؟ Can you use ORDER BY to sort results based on a column that is not included in the SELECT clause?
نعم، في معظم أنظمة قواعد البيانات العلائقية (مثل PostgreSQL و MySQL)، يمكنك الفرز بناءً على عمود موجود في الجدول حتى لو لم يتم استرجاعه في النتيجة.
Yes, in most RDBMS (like PostgreSQL and MySQL), you can sort by a column present in the table even if it is not projected in the SELECT clause.
8 أوامر تحديث البيانات (INSERT, DELETE, UPDATE)
8 Data Modification Statements (INSERT, DELETE, UPDATE)
الأوامر الثلاثة لتعديل حالة قاعدة البيانات: INSERT لإضافة صفوف، DELETE لحذفها، و UPDATE لتعديل القيم الحالية.
The three commands to modify database state: INSERT adds rows, DELETE removes them, and UPDATE modifies existing values.
هناك ثلاثة أوامر SQL لتعديل قاعدة البيانات:
- INSERT: لإضافة سجل أو أكثر. يمكن إدراج القيم مباشرة أو استخراجها من استعلام آخر.
- DELETE: لإزالة السجلات. يتضمن عادةً شرط WHERE؛ وبدونه يتم حذف جميع السجلات في الجدول.
- UPDATE: لتعديل قيم السجلات الحالية باستخدام جملة SET لتحديد القيم الجديدة، وجملة WHERE لتحديد السجلات المستهدفة.
يتم تطبيق قيود التكامل (Integrity Constraints) تلقائياً عند تنفيذ هذه الأوامر.
There are three SQL commands to modify the database:
- INSERT: adds one or more records. Values can be provided explicitly or via a query result.
- DELETE: removes records. It usually includes a WHERE clause; missing it deletes all tuples.
- UPDATE: modifies existing records using a SET clause for new values and a WHERE clause to select tuples.
Integrity constraints are automatically enforced during these operations.
في جملة UPDATE، عند الإشارة إلى نفس العمود على جانبي علامة التساوي (مثل SALARY = SALARY * 1.1)، فإن القيمة على اليمين تمثل القيمة القديمة قبل التعديل، والقيمة على اليسار تمثل القيمة الجديدة.
كما أن عمليات الحذف والتحديث قد تؤدي إلى تأثيرات متتالية (Cascading) إذا كانت هناك قيود مفاتيح أجنبية (Foreign Keys) معدة لذلك.
In an UPDATE statement, when referencing the same attribute on both sides of the '=' (e.g., SALARY = SALARY * 1.1), the right side refers to the old value, and the left side refers to the new value.
Furthermore, DELETE and UPDATE operations can trigger cascading effects if foreign key constraints (like ON DELETE CASCADE) are defined.
INSERT INTO EMPLOYEE (FNAME, LNAME, SSN) VALUES ('Richard', 'Marini', '653298653');
DELETE FROM EMPLOYEE WHERE DNO = 5;
UPDATE EMPLOYEE SET SALARY = SALARY * 1.1 WHERE DNO = 5;
ما هو الخطر الأكبر عند كتابة أمر DELETE أو UPDATE؟ What is the biggest risk when writing a DELETE or UPDATE statement?
نسيان جملة WHERE. بدونها، سيتم حذف أو تحديث جميع السجلات في الجدول بالكامل، مما قد يؤدي إلى كارثة في البيانات.
Forgetting the WHERE clause. Without it, the operation will delete or update every single record in the table, potentially causing a data disaster.