أساسيات SQL - الجزء الأول: تعريف البيانات والقيود
مقدمة إلى لغة الاستعلام المهيكلة (SQL)، مع التركيز على لغة تعريف البيانات (DDL)، أنواع البيانات، وإنشاء الجداول مع تحديد قيود التكامل المرجعي والمجال.
Basic SQL-1: Data Definition and Constraints
Introduction to Structured Query Language (SQL), focusing on Data Definition Language (DDL), data types, and creating tables with referential integrity and domain constraints.
أهداف التعلم
- شرح مفاهيم تعريف البيانات والقيود في لغة SQL.
- استخدام أوامر CREATE لإنشاء المخططات والجداول.
- تحديد أنواع البيانات المناسبة للسمات المختلفة (رقمية، نصية، كائنات كبيرة، وتاريخ/وقت).
- تطبيق قيود التكامل المرجعي (Referential Integrity) وحل مشكلة المراجع الدائرية.
- Explain data definition and constraints in SQL.
- Use CREATE statements to define schemas and tables.
- Select appropriate data types for various attributes (numeric, string, LOBs, and date/time).
- Apply referential integrity constraints and resolve the circular reference problem.
1 نظرة عامة وتاريخ SQL
1 Overview and History of SQL
لغة SQL هي اللغة القياسية الشاملة للتعامل مع قواعد البيانات العلائقية، بدأت باسم SEQUEL في شركة IBM.
SQL is the standard comprehensive language for relational databases, originally developed as SEQUEL at IBM.
لغة SQL (Structured Query Language) هي لغة قياسية تعتمد على النموذج العلائقي.
تتضمن قدرات متعددة مثل: لغة تعريف البيانات (DDL) لإنشاء المخططات وتحديد أنواع البيانات والقيود، أوامر استرجاع البيانات (SELECT)، أوامر تعديل البيانات (INSERT, DELETE, UPDATE)، وأوامر لإنشاء العروض (Views) والمشغلات (Triggers).
تطورت اللغة من SEQUEL في مشروع System-R التابع لـ IBM في السبعينيات، ومرت بعدة معايير مثل SQL-89، SQL-92، و SQL-99.
SQL is a standard, comprehensive language based on the relational model.
It includes capabilities for Data Definition Language (DDL) to create schemas and specify constraints, retrieval queries (SELECT), database modification (INSERT, DELETE, UPDATE), and specifying views, triggers, and assertions.
It was originally called SEQUEL, developed at IBM Research for the System-R relational DBMS in the 1970s, and evolved through standards like SQL-89, SQL-92, and SQL-99.
تطور معايير SQL يعكس الحاجة المتزايدة لدعم ميزات متقدمة مثل التوجه الكائني (Object-Oriented) في SQL-99 (المعروف أيضاً بـ SQL3).
تقسيم اللغة إلى DDL و DML يسمح بفصل هيكلة البيانات عن معالجتها، مما يعزز الأمان وإدارة الصلاحيات.
The evolution of SQL standards reflects the growing need to support advanced features, such as object-oriented concepts in SQL-99 (SQL3).
Separating the language into DDL and DML allows for the decoupling of database structure from data manipulation, enhancing security and access control.
لماذا تم تغيير اسم اللغة من SEQUEL إلى SQL؟ Why was the language renamed from SEQUEL to SQL?
تم تغييره لأسباب تتعلق بالعلامات التجارية، حيث كان اسم SEQUEL مسجلاً كعلامة تجارية لشركة أخرى.
It was changed due to trademark issues, as SEQUEL was already a trademark of another company.
2 إنشاء المخططات والجداول (CREATE SCHEMA & TABLE)
2 Creating Schemas and Tables (CREATE SCHEMA & TABLE)
أمر CREATE TABLE يبني هيكل الجدول ويحدد أسماء الأعمدة، أنواع بياناتها، والقيود الأساسية مثل المفتاح الأساسي.
The CREATE TABLE statement builds the table structure, defining column names, data types, and constraints like the Primary Key.
يُستخدم أمر CREATE SCHEMA لإنشاء قاعدة بيانات متميزة (مثال: CREATE SCHEMA COMPANY AUTHORIZATION 'Smith';).
بينما يُستخدم CREATE TABLE لتعريف علاقة أساسية جديدة من خلال تحديد اسمها، وسماتها، وأنواع بياناتها.
يمكن أيضاً تحديد قيود مثل NOT NULL، PRIMARY KEY، UNIQUE، و FOREIGN KEY داخل هذا الأمر.
إذا كانت هناك جداول متعددة، يمكن إضافة اسم المخطط كبادئة لاسم الجدول (مثال: COMPANY.EMPLOYEE).
The CREATE SCHEMA statement is used to create a distinct database (e.g., CREATE SCHEMA COMPANY AUTHORIZATION 'Smith';).
The CREATE TABLE statement specifies a new base relation by giving it a name and specifying its attributes and data types.
Constraints such as NOT NULL, PRIMARY KEY, UNIQUE, and FOREIGN KEY can also be defined here.
Table names can be prefixed by the schema name if multiple schemas exist (e.g., COMPANY.EMPLOYEE).
تحديد القيود أثناء إنشاء الجدول يضمن سلامة البيانات (Data Integrity) على مستوى محرك قاعدة البيانات (DBMS) بدلاً من الاعتماد على طبقة التطبيق.
استخدام AUTHORIZATION يربط المخطط بمالك محدد، مما يسهل إدارة الصلاحيات.
Defining constraints during table creation ensures data integrity at the DBMS level rather than relying on the application layer.
Using AUTHORIZATION binds the schema to a specific owner, facilitating access control management.
CREATE TABLE DEPARTMENT (
DNAME VARCHAR(15) NOT NULL,
DNUMBER INT NOT NULL,
MGRSSN CHAR(9) NOT NULL,
MGRSTARTDATE DATE,
PRIMARY KEY (DNUMBER),
UNIQUE (DNAME),
FOREIGN KEY(MGRSSN) REFERENCES EMPLOYEE);
ماذا يحدث إذا حاولنا إدخال قيمة فارغة (NULL) في عمود تم تعريفه كـ PRIMARY KEY؟ What happens if we try to insert a NULL value into a column defined as PRIMARY KEY?
سيرفض نظام إدارة قواعد البيانات العملية، لأن المفتاح الأساسي يتضمن ضمنياً قيد NOT NULL ويجب أن يكون فريداً.
The DBMS will reject the operation because a PRIMARY KEY implicitly includes a NOT NULL constraint and must be unique.
3 مشكلة المرجع الدائري
3 Circular Reference Problem
تحدث عندما يشير جدول (أ) إلى جدول (ب) بمفتاح أجنبي، وفي نفس الوقت يشير جدول (ب) إلى جدول (أ).
Occurs when Table A references Table B with a foreign key, and Table B simultaneously references Table A.
في مخطط قاعدة بيانات COMPANY، نجد أن جدول EMPLOYEE يحتوي على مفتاح أجنبي Dno يشير إلى DEPARTMENT.Dnumber، بينما يحتوي جدول DEPARTMENT على مفتاح أجنبي Mgr_ssn يشير إلى EMPLOYEE.Ssn.
هذا يخلق مشكلة عند إنشاء الجداول باستخدام CREATE TABLE، حيث لا يمكن إنشاء أي من الجدولين أولاً لأن كلاهما يعتمد على الآخر.
الحل هو إنشاء أحد الجدولين أولاً بدون قيد المفتاح الأجنبي (FOREIGN KEY)، ثم إضافة القيد المفقود لاحقاً باستخدام أمر ALTER TABLE.
In the COMPANY database schema, the EMPLOYEE table has a foreign key Dno referencing DEPARTMENT.Dnumber, while the DEPARTMENT table has a foreign key Mgr_ssn referencing EMPLOYEE.Ssn.
This creates a circular reference problem during table creation.
The solution is to create one of the tables first without the FOREIGN KEY constraint, and then add the missing FOREIGN KEY later using the ALTER TABLE statement.
هذه المشكلة تبرز أهمية فصل تعريف الهيكل (Table Definition) عن تعريف القيود (Constraint Definition).
في الأنظمة المعقدة، يُفضل غالباً إنشاء جميع الجداول الأساسية أولاً، ثم تشغيل سكريبت منفصل يضيف جميع قيود المفاتيح الأجنبية باستخدام ALTER TABLE لتجنب أي تعارضات في التبعية.
This problem highlights the importance of separating table definition from constraint definition.
In complex systems, it is often best practice to create all base tables first, and then run a separate script to add all foreign key constraints using ALTER TABLE to avoid any dependency conflicts.
هل يمكن حل مشكلة المرجع الدائري عن طريق إيقاف التحقق من المفاتيح الأجنبية مؤقتاً؟ Can the circular reference problem be solved by temporarily disabling foreign key checks?
نعم، في بعض أنظمة إدارة قواعد البيانات (مثل MySQL)، يمكن استخدام SET FOREIGN_KEY_CHECKS=0 قبل إنشاء الجداول، ثم إعادتها إلى 1.
Yes, in some DBMS (like MySQL), you can use SET FOREIGN_KEY_CHECKS=0 before creating tables, and then set it back to 1.
4 أنواع البيانات في SQL
4 SQL Data Types
توفر SQL أنواع بيانات متنوعة لتخزين الأرقام، النصوص، التواريخ، والكائنات الكبيرة (مثل الصور).
SQL provides various data types to store numbers, strings, dates, and large objects (like images).
تشمل أنواع البيانات الأساسية في SQL:
- الرقمية: الأعداد الصحيحة (
INTEGER,SMALLINT)، الأعداد الحقيقية (FLOAT,DOUBLE PRECISION)، والأرقام المنسقةDECIMAL(i, j)حيث i هي الدقة (إجمالي الخانات) و j هو المقياس (الخانات بعد الفاصلة). - النصية: ثابتة الطول
CHAR(n)ومتغيرة الطولVARCHAR(n). - المنطقية:
BIT(n). - الكائنات الكبيرة (LOBs):
BLOB(n)للبيانات الثنائية كالصور والفيديو، وCLOB(n)للنصوص الطويلة كالمقالات. - التاريخ والوقت:
DATE(yyyy-mm-dd)،TIME(hh:mm:ss)،TIMESTAMP(يجمع بين التاريخ والوقت)، وINTERVAL(لتمثيل فترة زمنية نسبية مثل 'سنتين و5 أشهر').
Basic SQL data types include:
- Numeric: Integers (
INTEGER,SMALLINT), Real/floating point (FLOAT,DOUBLE PRECISION), and FormattedDECIMAL(i, j)where i is precision (total digits) and j is scale (digits after decimal). - String: Fixed-length
CHAR(n)and Variable-lengthVARCHAR(n). - Boolean:
BIT(n). - Large Objects:
BLOB(n)for binary data like images/audio, andCLOB(n)for character data like articles. - Date/Time:
DATE(yyyy-mm-dd),TIME(hh:mm:ss),TIMESTAMP(combines date and time), andINTERVAL(represents a relative time period like '2 years and 5 months').
الفرق بين CHAR و VARCHAR مهم جداً لتحسين الأداء والمساحة.
CHAR يحجز المساحة كاملة حتى لو كان النص أقصر، مما يسرع البحث ولكنه يهدر المساحة.
VARCHAR يحجز فقط المساحة المطلوبة زائد بايت لتخزين الطول.
بالنسبة لـ TIMESTAMP، القيمة الافتراضية للكسور الثواني هي i=7.
The difference between CHAR and VARCHAR is crucial for performance and storage optimization.
CHAR pads the string with spaces to fill the length, which can speed up lookups but wastes space.
VARCHAR only uses the space needed plus a byte for length.
For TIMESTAMP, the default precision for fractional seconds is i=7.
| CHAR(n) | VARCHAR(n) | |
|---|---|---|
| استهلاك المساحةSpace Consumption | يحجز n بايت دائماً (يهدر المساحة)Always reserves n bytes (wastes space) | يحجز فقط المساحة المطلوبة + بايت للطولReserves only needed space + length byte |
| أفضل استخدامBest Use Case | البيانات ذات الطول الثابت (مثل رقم الهوية)Fixed-length data (e.g., SSN, Phone) | البيانات ذات الطول المتغير (مثل الأسماء)Variable-length data (e.g., Names, Addresses) |
إذا قمنا بتعريف حقل كـ DECIMAL(5,2)، ما هي أكبر قيمة يمكن تخزينها فيه؟ If we define a field as DECIMAL(5,2), what is the maximum value it can store?
أكبر قيمة هي 999.99 (5 خانات إجمالاً، منها 2 بعد الفاصلة).
The maximum value is 999.99 (5 total digits, 2 of which are after the decimal point).
5 خيارات التكامل المرجعي وتسمية القيود
5 Referential Integrity Options and Naming Constraints
تحدد خيارات التكامل المرجعي ما يحدث للسجلات المرتبطة عند حذف أو تحديث السجل الأساسي (مثل CASCADE لحذف السجلات المرتبطة تلقائياً).
Referential integrity options define what happens to related records when a parent record is deleted or updated (e.g., CASCADE to automatically delete related records).
عند تعريف مفتاح أجنبي، يمكننا تحديد الإجراء الذي يجب اتخاذه عند حذف (ON DELETE) أو تحديث (ON UPDATE) السجل المرجعي. الخيارات المتاحة هي:
- RESTRICT: (الافتراضي) يمنع الحذف/التحديث إذا كانت هناك سجلات مرتبطة.
- CASCADE: ينقل التغيير (حذف أو تحديث) تلقائياً إلى السجلات المرتبطة.
- SET NULL: يغير قيمة المفتاح الأجنبي في السجلات المرتبطة إلى NULL.
- SET DEFAULT: يغير قيمة المفتاح الأجنبي إلى القيمة الافتراضية المحددة.
كما يمكن إعطاء اسم للقيد باستخدام الكلمة المفتاحية CONSTRAINT (مثال: CONSTRAINT EMPPK PRIMARY KEY (Ssn))، مما يسهل حذفه لاحقاً باستخدام DROP CONSTRAINT.
When defining a foreign key, we can specify the action to take upon deletion (ON DELETE) or update (ON UPDATE) of the referenced record. The options are:
- RESTRICT: (The default) Prevents the delete/update if related records exist.
- CASCADE: Automatically propagates the change (delete or update) to related records.
- SET NULL: Sets the foreign key value in related records to NULL.
- SET DEFAULT: Sets the foreign key value to its specified default.
Constraints can also be named using the CONSTRAINT keyword (e.g., CONSTRAINT EMPPK PRIMARY KEY (Ssn)), which allows the constraint to be easily dropped later using DROP CONSTRAINT.
استخدام CASCADE خطير في قواعد البيانات الكبيرة لأنه قد يؤدي إلى حذف متسلسل غير مقصود لآلاف السجلات.
يُفضل استخدام RESTRICT أو SET NULL في الأنظمة المالية لتجنب فقدان البيانات التاريخية.
Using CASCADE can be dangerous in large databases as it might lead to unintended cascading deletions of thousands of records.
It is often safer to use RESTRICT or SET NULL in financial or critical systems to prevent loss of historical data.
CONSTRAINT EMPSUPERFK
FOREIGN KEY (Super_ssn) REFERENCES EMPLOYEE(Ssn)
ON DELETE SET NULL ON UPDATE CASCADE;
| RESTRICT | CASCADE | SET NULL | |
|---|---|---|---|
| السلوك عند الحذفBehavior on Delete | يمنع الحذفPrevents deletion | يحذف السجلات المرتبطةDeletes related records | يضع القيمة فارغةSets value to NULL |
متى يكون استخدام ON DELETE SET NULL غير مسموح به؟ When is using ON DELETE SET NULL not allowed?
لا يُسمح به إذا كان عمود المفتاح الأجنبي معرفاً بقيد NOT NULL.
It is not allowed if the foreign key column is defined with a NOT NULL constraint.
6 قيود المجال باستخدام CHECK و CREATE DOMAIN
6 Specifying DOMAIN Constraints Using CHECK and CREATE DOMAIN
تُستخدم CHECK لضمان أن القيم المدخلة في عمود معين تقع ضمن نطاق أو شرط محدد.
CHECK is used to ensure that values entered into a specific column fall within a defined range or condition.
يمكن تحديد قيود إضافية على البيانات باستخدام جملة CHECK.
على سبيل المثال، لضمان أن رقم القسم بين 1 و 20: CHECK (Dnumber > 0 AND Dnumber < 21).
بدلاً من تكرار هذا القيد في عدة جداول، يمكن إنشاء مجال مخصص باستخدام CREATE DOMAIN. مثال: CREATE DOMAIN D_NUM AS INTEGER CHECK (Dnumber > 0 AND Dnumber < 21);.
بعد ذلك، يمكن استخدام D_NUM كنوع بيانات لسمة Dnumber في جدول DEPARTMENT، ولسمة Dnum في جدول PROJECT، مما يسهل إعادة الاستخدام ويحافظ على اتساق البيانات.
Additional constraints on data can be specified using the CHECK clause.
For example, to ensure a department number is between 1 and 20: CHECK (Dnumber > 0 AND Dnumber < 21).
Instead of repeating this constraint across multiple tables, a custom domain can be created using CREATE DOMAIN. Example: CREATE DOMAIN D_NUM AS INTEGER CHECK (Dnumber > 0 AND Dnumber < 21);.
D_NUM can then be used as the data type for the Dnumber attribute in the DEPARTMENT table, and for Dnum in the PROJECT table, promoting reusability and consistency.
قيود CHECK توفر طريقة قوية لتطبيق قواعد العمل (Business Rules) مباشرة في قاعدة البيانات.
ومع ذلك، يجب الحذر من استخدام استعلامات فرعية (Subqueries) داخل CHECK لأن بعض أنظمة إدارة قواعد البيانات لا تدعمها أو قد تسبب بطئاً في الأداء.
CHECK constraints provide a powerful way to enforce business rules directly within the database.
However, one must be cautious about using subqueries inside a CHECK clause, as many DBMS do not support them or they can cause significant performance overhead.
CREATE DOMAIN D_NUM AS INTEGER CHECK (Dnumber > 0 AND Dnumber < 21);
ما هي الميزة الرئيسية لاستخدام CREATE DOMAIN بدلاً من كتابة CHECK في كل جدول؟ What is the main advantage of using CREATE DOMAIN instead of writing CHECK in every table?
إعادة الاستخدام وسهولة الصيانة؛ إذا تغيرت قاعدة العمل، نقوم بتحديث المجال مرة واحدة فقط بدلاً من تعديل كل جدول.
Reusability and maintainability; if the business rule changes, you only update the domain once instead of modifying every table.