See different links to revise typing SQL queries:
Oracle SQL Basics (Highly Recommended)
Welcome to the Introduction to SQL repository! This resource is designed to provide a foundational understanding of Structured Query Language (SQL), focusing on core concepts and practical implementation using Oracle SQL syntax.
ملحوظة: الشرح المبسّط الموجود بين قوسين
- What is SQL?
- SQL Command Categories (DDL, DML, DQL)
- Table Column Definitions
- Table Creation and Data Manipulation
- Data Querying (DQL)
- Joining Multiple Tables
- Nested Queries (Subqueries)
- Performance and Structure Tools
SQL (Structured Query Language) is a standard language for managing data held in a Relational Database Management System (RDBMS). It is used to perform tasks such as updating, inserting, deleting, and retrieving data from a database.
SQL commands are broadly categorized based on their function:
| Category | Full Form | Purpose | Example Commands |
|---|---|---|---|
| DDL | Data Definition Language | Defines, modifies, and deletes database objects (like tables, indexes, views). | CREATE, ALTER, DROP |
| DML | Data Manipulation Language | Manages data within schema objects. | INSERT, UPDATE, DELETE |
| DQL | Data Query Language | Used for retrieving data from the database. | SELECT |
| TCL | Transaction Control Language | Manages transactions (groups of DML statements). | COMMIT, ROLLBACK |
تقسيمة الأوامر: الـ DDL بتلعب في هيكل الداتابيز (بتبني أو بتغير الجدول). الـ DML بتلعب في البيانات اللي جوه الجدول (بتضيف أو بتعدل صفوف). والـ DQL هي بتاعة الاستعلام بس).
Datatypes define the type of data a column can hold (e.g., text, numbers, dates).
| Datatype (Oracle) | Description | Example Use |
|---|---|---|
VARCHAR2(size) |
Variable-length character string (text). | NAME VARCHAR2(100) |
NUMBER(p, s) |
Numeric value (p = precision, s = scale). | SALARY NUMBER(8, 2) |
DATE |
Stores date and time. | HIRE_DATE DATE |
Constraints enforce rules on the data columns to ensure data integrity.
Ensures that all values in a column or a group of columns are different.
CREATE TABLE Employees (
employee_id NUMBER,
email VARCHAR2(100) UNIQUE
);Ensures that a column cannot have a NULL value.
CREATE TABLE Employees (
employee_id NUMBER,
last_name VARCHAR2(50) NOT NULL
);Uniquely identifies each row in a table. It is a combination of UNIQUE and NOT NULL.
CREATE TABLE Departments (
dept_id NUMBER PRIMARY KEY,
dept_name VARCHAR2(50) NOT NULL
);A column (or collection of columns) in one table that refers to the Primary Key in another table. It links two tables and maintains referential integrity.
CREATE TABLE Employees (
employee_id NUMBER PRIMARY KEY,
...
dept_id NUMBER,
CONSTRAINT fk_dept
FOREIGN KEY (dept_id)
REFERENCES Departments(dept_id)
);| Feature | Primary Key (PK) | Foreign Key (FK) |
|---|---|---|
| Purpose | Uniquely identify a record (row) in a table. | Link two tables; enforce referential integrity. |
| Constraint | Must be UNIQUE and NOT NULL. | Can contain duplicates and may be NULL (unless specified otherwise). |
| Table Count | Only one PK per table. | A table can have multiple FKs. |
CREATE TABLE Products (
product_id NUMBER PRIMARY KEY,
product_name VARCHAR2(100) NOT NULL,
price NUMBER(6, 2),
supplier_id NUMBER,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES Suppliers(supplier_id)
);INSERT INTO Products (product_id, product_name, price, supplier_id)
VALUES (101, 'Laptop', 1200.00, 50);-- Increase the size of the product_name column
ALTER TABLE Products
MODIFY (product_name VARCHAR2(150));-- Add a new column for product description
ALTER TABLE Products
ADD (product_description VARCHAR2(500));| Command | Category | Purpose | Syntax |
|---|---|---|---|
DELETE |
DML | Removes rows from a table. Can be rolled back. | DELETE FROM Products WHERE product_id = 101; |
TRUNCATE |
DDL | Removes all rows from a table quickly. Cannot be rolled back. | TRUNCATE TABLE Products; |
DROP |
DDL | Permanently removes the entire table structure and data from the database. | DROP TABLE Products; |
The fundamental command for retrieving data.
-- Retrieve all columns and all rows from the Employees table
SELECT * FROM Employees;-
DISTINCT: Eliminates duplicate rows from the result set.$(\text{بيصفي النتايج وبيجيب القيم الفريدة فقط.})$ -
FETCH: Limits the number of rows returned by a query (often used withORDER BY).$(\text{بيحدد عدد الصفوف اللي ترجعلك في النتيجة، مفيد عشان تجيب 'أول 10' مثلاً.})$
-- Get unique department IDs
SELECT DISTINCT dept_id FROM Employees;
-- Get the top 10 most highly paid employees (Oracle 12c+ syntax)
SELECT employee_id, salary
FROM Employees
ORDER BY salary DESC
FETCH FIRST 10 ROWS ONLY;Filters records based on a specified condition.
-- Find employees with a salary greater than 50000
SELECT last_name, salary
FROM Employees
WHERE salary > 50000;Used within the WHERE clause to form conditions:
| Type | Operator | Description | Example |
|---|---|---|---|
| Comparison | =, != (<>), >, <, >=, <= |
Test equality/inequality/magnitude. | WHERE salary = 60000 |
| Logical | AND, OR, NOT |
Combine multiple conditions. | WHERE dept_id = 50 AND salary > 50000 |
Perform a calculation on a set of rows and return a single summary value.
| Function | Description | Example |
|---|---|---|
COUNT() |
Number of rows. | COUNT(*) |
SUM() |
Sum of values. | SUM(salary) |
AVG() |
Average of values. | AVG(salary) |
-- Get the average salary across the company
SELECT AVG(salary) AS avg_salary FROM Employees;-
GROUP BY: Groups rows that have the same values in specified columns into summary rows.$(\text{بتجمع الصفوف المتشابهة في مجموعة عشان تطبق عليها دوال التجميع.})$ -
ORDER BY: Sorts the result set by one or more columns.$(\text{بتنظم النتايج يا تصاعدي } (\text{ASC}) \text{ يا تنازلي } (\text{DESC}).)$
-- Calculate the total salary for each department, sorted by total salary
SELECT dept_id, SUM(salary) AS total_dept_salary
FROM Employees
GROUP BY dept_id
ORDER BY total_dept_salary DESC;-
HAVING: Filters groups created by theGROUP BYclause.$(\text{بتفلتر المجموعات اللي عملها } \text{GROUP BY} \text{، ودي لازم تستخدم فيها دالة تجميع.})$ -
WHERE: Filters individual rows before they are grouped.$(\text{بتفلتر الصفوف قبل ما تتجمع.})$
-- Find departments where the total salary expense is over 500,000
SELECT dept_id, SUM(salary) AS total_dept_salary
FROM Employees
GROUP BY dept_id
HAVING SUM(salary) > 500000;| Feature | WHERE Clause |
HAVING Clause |
|---|---|---|
| Execution | Executes before GROUP BY. |
Executes after GROUP BY. |
| Applicability | Filters individual rows. | Filters aggregated groups. |
| Operator | Description | Example |
|---|---|---|
LIKE |
Used for pattern matching. |
WHERE last_name LIKE 'Smi%' |
IN |
Used to specify multiple possible values for a column. |
WHERE dept_id IN (10, 20, 30) |
BETWEEN |
Used to select values within a given range (inclusive). |
WHERE salary BETWEEN 50000 AND 75000 |
Aliases are temporary names given to a table or a column to make the query easier to read and manage.
-- Column Alias
SELECT employee_id AS ID, last_name "Employee Name"
FROM Employees;
-- Table Alias
SELECT e.last_name, d.dept_name
FROM Employees e, Departments d
WHERE e.dept_id = d.dept_id;A powerful tool for performing conditional logic (IF/THEN/ELSE) directly within a query.
$(\text{بتعمل شرط جوه جملة الـ SELECT نفسها، بتقول: لو الشرط ده اتحقق، طلع القيمة دي، وإلا طلع القيمة دي.})$
SELECT
last_name,
CASE
WHEN salary < 50000 THEN 'Low'
ELSE 'High'
END AS Salary_Level
FROM Employees;Joins combine rows from two or more tables based on a related column between them.
Returns only the rows that have matching values in both tables.
SELECT e.last_name, d.dept_name
FROM Employees e
INNER JOIN Departments d ON e.dept_id = d.dept_id;Returns all rows from both tables, with NULL values where there is no match in the other table.
SELECT e.last_name, d.dept_name
FROM Employees e
FULL OUTER JOIN Departments d ON e.dept_id = d.dept_id;-
Left Join: Returns all rows from the left table and the matched rows from the right table.
$(\text{بتجيب كل بيانات الجدول الشمال } (\text{Left}) \text{ والصفوف اللي ليها ماتش من الجدول اليمين.})$ -
Right Join: Returns all rows from the right table and the matched rows from the left table.
$(\text{العكس، بتجيب كل بيانات الجدول اليمين.})$
-- Left Join
SELECT e.last_name, d.dept_name
FROM Employees e
LEFT JOIN Departments d ON e.dept_id = d.dept_id;A join of a table to itself. This is often used when a table has a foreign key that references its own primary key.
-- Find the name of each employee's manager
SELECT worker.last_name AS Employee, manager.last_name AS Manager
FROM Employees worker
JOIN Employees manager ON worker.manager_id = manager.employee_id;A subquery is a query nested inside another query. They are used to return data that will be used by the outer query.
-- Find employees whose salary is greater than the average salary of all employees
SELECT last_name, salary
FROM Employees
WHERE salary > (
SELECT AVG(salary) FROM Employees
);Indexes are special lookup tables that the database search engine can use to speed up data retrieval.
-- Create an index on the last_name column
CREATE INDEX idx_emp_lastname
ON Employees (last_name);A view is a stored query that acts like a virtual table. It doesn't store data itself but displays data from the underlying tables.
-- Create a view that only shows employee names and their department names
CREATE VIEW Employee_Department_View AS
SELECT e.last_name, d.dept_name
FROM Employees e
JOIN Departments d ON e.dept_id = d.dept_id;
-- You can query the view just like a table
SELECT * FROM Employee_Department_View;