0% found this document useful (0 votes)
42 views30 pages

SQL Fundmentals

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views30 pages

SQL Fundmentals

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

‫?

‪SQL language‬‬
‫هي اختصار لجملة ‪structured query language‬‬

‫يتيح لك ‪ SQL‬الوصول إلى قواعد البيانات والتعامل معها‬ ‫‪‬‬


‫أصبحت ‪ SQL‬معياًر ا للمعهد الوطني األمريكي للمعايير (‪ )ANSI‬في عام ‪،1986‬‬ ‫‪‬‬
‫والمنظمة الدولية للمعايير (‪ )ISO‬في عام ‪.1987‬‬

‫‪?What can SQL do‬‬

‫يمكن لـ ‪ SQL‬تنفيذ االستعالمات على قاعدة البيانات‬ ‫‪‬‬


‫يمكن لـ ‪ SQL‬استرداد البيانات من قاعدة البيانات‬ ‫‪‬‬
‫يمكن لـ ‪ SQL‬إدراج السجالت في قاعدة البيانات‬ ‫‪‬‬
‫يمكن لـ ‪ SQL‬تحديث السجالت في قاعدة البيانات‬ ‫‪‬‬
‫يمكن لـ ‪ SQL‬حذف السجالت من قاعدة البيانات‬ ‫‪‬‬
‫يمكن لـ ‪ SQL‬إنشاء قواعد بيانات جديدة‬ ‫‪‬‬
‫يمكن لـ ‪ SQL‬إنشاء جداول جديدة في قاعدة البيانات‬ ‫‪‬‬
‫يمكن لـ ‪ SQL‬إنشاء اإلجراءات المخزنة في قاعدة البيانات‬ ‫‪‬‬
‫يمكن لـ ‪ SQL‬إنشاء طرق عرض في قاعدة البيانات‬ ‫‪‬‬
‫يمكن لـ ‪ SQL‬تعيين األذونات على الجداول واإلجراءات وطرق العرض‬ ‫‪‬‬

‫‪RDBMS‬‬

‫‪Relational Database Management System‬‬

‫نظام إدارة قواعد البيانات المرتبطة‬

‫يتم تخزين البيانات الموجودة في ‪ RDBMS‬في كائنات قاعدة بيانات تسمى الجداول‪ .‬الجدول‬
‫عبارة عن مجموعة من إدخاالت البيانات المرتبطة ويتكون من أعمدة وصفوف‪.‬‬

‫يتم تقسيم كل جدول إلى كيانات أصغر تسمى الحقول‪ .‬تتكون الحقول الموجودة في جدول‬
‫العمالء من معرف العميل واسم العميل واسم جهة االتصال والعنوان والمدينة والرمز البريدي‬
‫والبلد‪ .‬الحقل هو عمود في جدول مصمم لالحتفاظ بمعلومات محددة حول كل سجل في‬
‫الجدول‪.‬‬

‫السجل‪ ،‬الذي يسمى أيًض ا الصف‪ ،‬هو كل إدخال فردي موجود في الجدول‪ .‬على سبيل المثال‪،‬‬
‫يوجد ‪ 91‬سجًال في جدول العمالء أعاله‪ .‬السجل هو كيان أفقي في الجدول‪.‬‬

‫العمود هو كيان رأسي في جدول يحتوي على كافة المعلومات المرتبطة بحقل معين في‬
‫الجدول‪.‬‬
SQL Syntax

Most of the actions you need to perform on a database are done with SQL
statements.

SQL statements consists of keywords that are easy to understand.

The following SQL statement returns all records from a table named
"Customers":

Example

Select all records from the Customers table:

SELECT * FROM Customers;

Database Tables

‫ يتم تعريف كل جدول باسم (على سبيل‬.‫تحتوي قاعدة البيانات غالًبا على جدول واحد أو أكثر‬
.‫ ويحتوي على سجالت (صفوف) تحتوي على بيانات‬،)"‫ "العمالء" أو "الطلبات‬،‫المثال‬

‫ المعروفة (المضمنة‬Northwind ‫ سنستخدم نموذج قاعدة بيانات‬،‫في هذا البرنامج التعليمي‬


.)MS SQL Server‫ و‬MS Access ‫في‬

،‫يحتوي الجدول أعاله على خمسة سجالت (واحد لكل عميل) وسبعة أعمدة (معرف العميل‬
.)‫ والدولة‬،‫ والرمز البريدي‬،‫ والمدينة‬،‫ والعنوان‬،‫ واسم جهة االتصال‬،‫واسم العميل‬
SELECT - extracts data from a database.

UPDATE - updates data in a database.

DELETE - deletes data from a database.

INSERT INTO - inserts new data into a database.

CREATE DATABASE - creates a new database.

ALTER DATABASE - modifies a database.

CREATE TABLE - creates a new table.

ALTER TABLE - modifies a table.

DROP TABLE - deletes a table.

CREATE INDEX - creates an index (search key)

DROP INDEX - deletes an index.

The SQL SELECT Statement

The SELECT statement is used to select data from a database.


The SQL SELECT DISTINCT Statement

The SELECT DISTINCT statement is used to return only distinct (different)


values.

The SQL WHERE Clause

The WHERE clause is used to filter records.

It is used to extract only those records that fulfil a specified condition.

Text Fields vs. Numeric Fields

SQL requires single quotes around text values (most database systems
will also allow double quotes).

However, numeric fields should not be enclosed in quotes:


The SQL ORDER BY
The ORDER BY keyword is used to sort the result-set in ascending or
descending order.

.‫ لفرز مجموعة النتائج بترتيب تصاعدي أو تنازلي‬ORDER BY ‫يتم استخدام الكلمة األساسية‬

SELECT * FROM Products


ORDER BY Price;

DESC

The ORDER BY keyword sorts the records in ascending order by default. To


sort the records in descending order, use the DESC keyword.
Order Alphabetically

For string values the ORDER BY keyword will order alphabetically:

Alphabetically DESC

To sort the table reverse alphabetically, use the DESC keyword:

ORDER BY Several Columns

The following SQL statement selects all customers from the "Customers"
table, sorted by the "Country" and the "Customer Name" column. This
means that it orders by Country, but if some rows have the same Country,
it orders them by Customer Name:
The SQL AND Operator
The WHERE clause can contain one or many AND operators.

The AND operator is used to filter records based on more than one
condition, like if you want to return all customers from Spain that starts
with the letter 'G':

‫ مثل إذا‬،‫ لتصفية السجالت بناًء على أكثر من شرط واحد‬AND ‫يتم استخدام عامل التشغيل‬
:"G" ‫كنت تريد إرجاع جميع العمالء من إسبانيا الذين يبدأون بالحرف‬

Example

Select all Spanish customers that starts with either "G" or "R":

The SQL OR Operator


The WHERE clause can contain one or more OR operators.

The OR operator is used to filter records based on more than one


condition, like if you want to return all customers from Germany but also
those from Spain:
‫ مثل إذا كنت‬، ‫يتم استخدام أو المشغل لتصفية السجالت استناًدا إلى أكثر من حالة واحدة‬
:‫ترغب في إعادة جميع العمالء من ألمانيا وأيًض ا من إسبانيا‬

At Least One Condition Must Be True

The following SQL statement selects all fields from Customers where
either City is "Berlin", Customer Name starts with the letter "G"
or Country is "Norway":

The NOT Operator


The NOT operator is used in combination with other operators to give the
opposite result, also called the negative result.

In the select statement below we want to return all customers that are
NOT from Spain:
The SQL INSERT INTO Statement
The INSERT INTO statement is used to insert new records in a table.

INSERT INTO Syntax

It is possible to write the INSERT INTO statement in two ways:

1. Specify both the column names and the values to be inserted:

2. If you are adding values for all the columns of the table, you do not
need to specify the column names in the SQL query. However, make sure
the order of the values is in the same order as the columns in the table.
Here, the INSERT INTO syntax would be as follows:

What is a NULL Value?

A field with a NULL value is a field with no value.

How to Test for NULL Values?

It is not possible to test for NULL values with comparison operators, such
as =, <, or <>.

We will have to use the IS NULL and IS NOT NULL operators instead.
The SQL UPDATE Statement
The UPDATE statement is used to modify the existing records in a table.

The SQL DELETE Statement

The DELETE statement is used to delete existing records in a table.


The SQL SELECT TOP Clause
The SELECT TOP clause is used to specify the number of records to return.

The SELECT TOP clause is useful on large tables with thousands of


records. Returning a large number of records can impact performance.

SQL Aggregate Functions

An aggregate function is a function that performs a calculation on a set of


values, and returns a single value.

Aggregate functions are often used with the GROUP BY clause of


the SELECT statement. The GROUP BY clause splits the result-set into
groups of values and the aggregate function can be used to return a
single value for each group.

،‫الدالة التجميعية هي دالة تقوم بإجراء عملية حسابية على مجموعة من القيم‬
‫وترجع قيمة واحدة‬.
‫ غالًبا ما يتم استخدام الداالت التجميعية مع عبارة‬GROUP BY ‫الخاصة بعبارة‬
SELECT. ‫ تقوم جملة‬GROUP BY ‫بتقسيم مجموعة النتائج إلى مجموعات من‬
‫القيم ويمكن استخدام الدالة التجميعية إلرجاع قيمة واحدة لكل مجموعة‬.
The most commonly used SQL aggregate functions are:

 MIN() - returns the smallest value within the selected column.

 MAX() - returns the largest value within the selected column.

 COUNT() - returns the number of rows in a set.

 SUM() - returns the total sum of a numerical column.

 AVG() - returns the average value of a numerical column.

Aggregate functions ignore null values (except for COUNT()).


The SQL MIN() and MAX() Functions

The MIN() function returns the smallest value of the selected column.

The MAX() function returns the largest value of the selected column.

The SQL COUNT() Function

The COUNT() function returns the number of rows that matches a


specified criterion.

The SQL SUM() Function

The SUM() function returns the total sum of a numeric column.

The SQL AVG() Function

The AVG() function returns the average value of a numeric column.


The SQL LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified
pattern in a column.

There are two wildcards often used in conjunction with the LIKE operator:

 The percent sign % represents zero, one, or multiple characters

 The underscore sign _ represents one, single character


The SQL IN Operator
The IN operator allows you to specify multiple values in
a WHERE clause.

The IN operator is a shorthand for multiple OR conditions

NOT IN

By using the NOT keyword in front of the IN operator, you return all
records that are NOT any of the values in the list.

The SQL BETWEEN Operator


The BETWEEN operator selects values within a given range. The values
can be numbers, text, or dates.

The BETWEEN operator is inclusive: begin and end values are included.
BETWEEN Dates

The following SQL statement selects all orders with an OrderDate


between '01-July-1996' and '31-July-1996':

Or

AS is Optional

Actually, in most database languages, you can skip the AS keyword and
get the same result:

Concatenate Columns

The following SQL statement creates an alias named "Address" that


combine four columns (Address, PostalCode, City and Country):
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based
on a related column between them.

‫ بناًء على عمود مرتبط بينهما‬،‫ لدمج صفوف من جدولين أو أكثر‬JOIN ‫يتم استخدام جملة‬

Let's look at a selection from the "Orders" table:

Different Types of SQL JOINs

Here are the different types of the JOINs in SQL:

 (INNER) JOIN: Returns records that have matching values in both


tables

 LEFT (OUTER) JOIN: Returns all records from the left table, and the
matched records from the right table

 RIGHT (OUTER) JOIN: Returns all records from the right table, and
the matched records from the left table

 FULL (OUTER) JOIN: Returns all records when there is a match in


either left or right table

SQL FULL OUTER JOIN Keyword


The FULL OUTER JOIN keyword returns all records when there is a
match in left (table1) or right (table2) table records.

Tip: FULL OUTER JOIN and FULL JOIN are the same.
SQL ‫الكلمة األساسية الكاملة للصلة الخارجية‬

‫ بإرجاع كافة السجالت عندما يكون هناك‬FULL OUTER JOIN ‫تقوم الكلمة األساسية‬
.)2 ‫) أو األيمن (الجدول‬1 ‫تطابق في سجالت الجدول األيسر (الجدول‬

SQL Self Join


A self join is a regular join, but the table is joined with itself.

The SQL UNION Operator


The UNION operator is used to combine the result-set of two or
more SELECT statements.

 Every SELECT statement within UNION must have the same number
of columns

 The columns must also have similar data types

 The columns in every SELECT statement must also be in the same


order

SQL UNION ‫مشغل‬

SELECT ‫ لدمج مجموعة النتائج المكونة من عبارات‬UNION ‫يتم استخدام عامل التشغيل‬
.‫أو أكثر‬

‫ على نفس عدد األعمدة‬UNION ‫ داخل‬SELECT ‫يجب أن تحتوي كل عبارة‬

‫يجب أن تحتوي األعمدة أيًض ا على أنواع بيانات مماثلة‬


‫ بنفس الترتيب‬SELECT ‫يجب أيًض ا أن تكون األعمدة الموجودة في كل عبارة‬
The SQL GROUP BY Statement
The GROUP BY statement groups rows that have the same values into
summary rows, like "find the number of customers in each country".

The GROUP BY statement is often used with aggregate functions


(COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or
more columns.

SQL GROUP BY ‫بيان‬

‫ مثل‬،‫ بتجميع الصفوف التي لها نفس القيم في صفوف ملخص‬GROUP BY ‫تقوم عبارة‬
."‫"ابحث عن عدد العمالء في كل بلد‬

COUNT()، MAX()،( ‫ مع الوظائف التجميعية‬GROUP BY ‫غالًبا ما يتم استخدام عبارة‬


.‫()) لتجميع مجموعة النتائج حسب عمود واحد أو أكثر‬MIN()، SUM()، AVG

The SQL CREATE DATABASE Statement


The CREATE DATABASE statement is used to create a new SQL
database.
The SQL DROP DATABASE Statement

The DROP DATABASE statement is used to drop an existing SQL


database.

The SQL BACKUP DATABASE Statement

The BACKUP DATABASE statement is used in SQL Server to create a full


back up of an existing SQL database.

BACKUP WITH DIFFERENTIAL Example


Tip: A differential back up reduces the back up time (since only the changes
are backed up).

The SQL CREATE TABLE Statement

The CREATE TABLE statement is used to create a new table in a


database.

The column parameters specify the names of the columns of the table.

The datatype parameter specifies the type of data the column can hold
(e.g. varchar, integer, date, etc.).

Tip: For an overview of the available data types, go to our


complete Data Types Reference.

The SQL DROP TABLE Statement

The DROP TABLE statement is used to drop an existing table in a


database.

SQL TRUNCATE TABLE


The TRUNCATE TABLE statement is used to delete the data inside a
table, but not the table itself.

SQL ALTER TABLE Statement

The ALTER TABLE statement is used to add, delete, or modify columns


in an existing table.

The ALTER TABLE statement is also used to add and drop various
constraints on an existing table.

.‫ إلضافة أو حذف أو تعديل األعمدة في جدول موجود‬ALTER TABLE ‫يتم استخدام عبارة‬

.‫ أيًض ا إلضافة وإسقاط قيود مختلفة على جدول موجود‬ALTER TABLE ‫يتم استخدام عبارة‬

ADD Column

To add a column in a table, use the following syntax:

DROP COLUMN

To delete a column in a table, use the following syntax (notice that


some database systems don't allow deleting a column):

RENAME COLUMN

To rename a column in a table, use the following syntax:


ALTER TABLE - ALTER/MODIFY DATATYPE

To change the data type of a column in a table, use the following


syntax:

SQL Create Constraints

Constraints can be specified when the table is created with the CREATE
TABLE statement, or after the table is created with the ALTER
TABLE statement.

The following constraints are commonly used in SQL:

 NOT NULL - Ensures that a column cannot have a NULL value

 UNIQUE - Ensures that all values in a column are different


 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely
identifies each row in a table

 FOREIGN KEY - Prevents actions that would destroy links between


tables

 CHECK - Ensures that the values in a column satisfies a specific


condition

 DEFAULT - Sets a default value for a column if no value is specified

 CREATE INDEX - Used to create and retrieve data from the database
very quickly

SQL UNIQUE Constraint


The UNIQUE constraint ensures that all values in a column are different.

Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for
uniqueness for a column or set of columns.

A PRIMARY KEY constraint automatically has a UNIQUE constraint.

However, you can have many UNIQUE constraints per table, but only
one PRIMARY KEY constraint per table.

SQL UNIQUE Constraint on CREATE TABLE


The following SQL creates a UNIQUE constraint on the "ID" column
when the "Persons" table is created:

SQL Server / Oracle / MS Access:

DROP a UNIQUE Constraint


To drop a UNIQUE constraint, use the following SQL:
SQL PRIMARY KEY Constraint
The PRIMARY KEY constraint uniquely identifies each record in a table.

Primary keys must contain UNIQUE values, and cannot contain NULL
values.

A table can have only ONE primary key; and in the table, this primary
key can consist of single or multiple columns (fields)

SQL PRIMARY KEY on CREATE TABLE

The following SQL creates a PRIMARY KEY on the "ID" column when the
"Persons" table is created:

MySQL:

SQL Server / Oracle / MS Access:


SQL PRIMARY KEY on ALTER TABLE

To create a PRIMARY KEY constraint on the "ID" column when the table
is already created, use the following SQL:

MySQL / SQL Server / Oracle / MS Access:

To allow naming of a PRIMARY KEY constraint, and for defining


a PRIMARY KEY constraint on multiple columns, use the following SQL
syntax:

DROP a PRIMARY KEY Constraint

To drop a PRIMARY KEY constraint, use the following SQL:

MySQL:

ALTER TABLE Persons


DROP PRIMARY KEY;

SQL Server / Oracle / MS Access:

ALTER TABLE Persons


DROP CONSTRAINT PK_Person;

SQL FOREIGN KEY Constraint


The FOREIGN KEY constraint is used to prevent actions that would
destroy links between tables.

A FOREIGN KEY is a field (or collection of fields) in one table, that refers
to the PRIMARY KEY in another table.

The table with the foreign key is called the child table, and the table
with the primary key is called the referenced or parent table.
Look at the following two tables:

Notice that the "PersonID" column in the "Orders" table points to the
"PersonID" column in the "Persons" table.

The "PersonID" column in the "Persons" table is the PRIMARY KEY in the
"Persons" table.

The "PersonID" column in the "Orders" table is a FOREIGN KEY in the


"Orders" table.

The FOREIGN KEY constraint prevents invalid data from being inserted
into the foreign key column, because it has to be one of the values
contained in the parent table.

The following SQL creates a FOREIGN KEY on the "PersonID" column


when the "Orders" table is created:

MySQL:

CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);
SQL Server / Oracle / MS Access:

CREATE TABLE Orders (


OrderID int NOT NULL PRIMARY KEY,
OrderNumber int NOT NULL,
PersonID int FOREIGN KEY REFERENCES Persons(PersonID)
);

To allow naming of a FOREIGN KEY constraint, and for defining


a FOREIGN KEY constraint on multiple columns, use the following SQL
syntax:

MySQL / SQL Server / Oracle / MS Access:

SQL FOREIGN KEY on ALTER TABLE

To create a FOREIGN KEY constraint on the "PersonID" column when the


"Orders" table is already created, use the following SQL:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Orders


ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

To allow naming of a FOREIGN KEY constraint, and for defining


a FOREIGN KEY constraint on multiple columns, use the following SQL
syntax:

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Orders


ADD CONSTRAINT FK_PersonOrder
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

DROP a FOREIGN KEY Constraint

To drop a FOREIGN KEY constraint, use the following SQL:


MySQL:

You might also like