Welcome to SQL E-Learning
Unlock your potential with our expertly crafted SQL courses. Whether
you're a beginner or looking to deepen your understanding, we have
the resources you need. Our platform offers:
-
Interactive Courses: Hands-on SQL exercises to practice and
solidify your knowledge.
-
Real-world Projects: Work on projects that simulate real
database scenarios.
-
Expert Guidance: Learn from industry professionals with years of
experience.
-
Flexible Learning: Access courses at your own pace, anytime and
anywhere.
Get started today and become proficient in SQL, the language of
data!
Join Now to Explore Our Courses!
Introduction To SQL
SQL - Structured Quiry Language
What is SQL?
- SQL stands for Structured Query Language
- SQL lets you access and manipulate databases
-
SQL became a staxcndard of the American National Standards
Institute (ANSI) in 1986, and of the International Organization
for Standardization (ISO) in 1987
SQL(Structured Query Language) has been around for a long time now and
yet it is still the most prevalent query language developed for
communicating with databases. The benefits of SQL comprise revising
database tables and index structures; incorporating, revamping, and
deleting rows of data; and recovering subsets of data from within a
database for the purpose of transaction processing and analytics
applications. SQL was designed by IBM in the early 1970s.
Its capability to run queries including retrieve, incorporate, revise,
and delete was astounding and compelling to future technologies like
RESTful APIs and CRUD (Create, Read, Update, and Delete). In this
article, we will discuss a few of the fantastic SQL books. With these
books, you can learn more about SQL quickly and evolve as an
indispensable programmer or data analyst.
SQL Syntax details.
1. Basic SQL Syntax
- SQL Statement Structure: SELECT, INSERT, UPDATE, DELETE .
-
Case Sensitivity: SQL keywords are case-insensitive, but
conventions typically use uppercase for readability.
- Semicolon (;): Ends SQL statements (optional in some DBMS).
2 . Data Types
In SQL, data types specify the kind of data that a column can hold in
a database table. Choosing the correct data type ensures that the
database stores data efficiently and maintains data integrity.
Different data types are used for storing different types of
information like numbers, text, dates, etc.
The Following Are The Types Of DataTypes Available In SQL
- Integer (INT)
- String (VARCHAR, CHAR)
- Float (FLOAT, DECIMAL)
- Date and Time (DATE, TIME, DATETIME)
- Boolean (BOOLEAN)
3. Comments
In SQL, comments are non-executable parts of the code used to explain,
document, or temporarily disable portions of the query. They are
especially helpful in making the SQL code more understandable for
others or for future reference.
- Single-line comments (-- Comment)
- Multi-line comments (/* Comment */)
SQL Select Statement .
The SELECT statement in SQL is used to retrieve data from a database.
It's one of the most commonly used SQL commands, as it allows you to
specify exactly which data you want to see from one or more database
tables
Syntax
Basic Syntax of the SELECT Statement:
2. Selects All Column records from the Specified table:
SELECT * FROM table_name ;
Examples
Consider A Table Costumer For Example . Having Following Data
in the Table
| Customer ID |
First_Name |
Last_Name |
Country |
| 1 |
John |
Doe |
USA |
| 2 |
Jane |
Smith |
UK |
| 3 |
Michael |
Brown |
Canada |
| 4 |
Emily |
Jones |
Australia |
1. Selects the specified Column records from the Specified
SELECT First_Name ,Last_Name FROM Customer;
OutPut
| First_Name |
Last_Name |
| John |
Doe |
| Jane |
Smith |
| Michael |
Brown |
| Emily |
Jones |
2. Selects All Column records from the Specified table:
SELECT * FROM Customer ;
OutPut
| Customer ID |
First_Name |
Last_Name |
Country |
| 1 |
John |
Doe |
USA |
| 2 |
Jane |
Smith |
UK |
| 3 |
Michael |
Brown |
Canada |
| 4 |
Emily |
Jones |
Australia |
SQL DISTINCT Select Statement .
The SQL DISTINCT statement is used to return only unique (distinct)
values from a column or set of columns. This helps eliminate duplicate
rows from the result set.
Syntax
This Will Return Only unique value of The Specified Column Of The
Table
SELECT DISTINCT column_name FROM Table_name;
Exmaple
| Customer ID |
First_Name |
Last_Name |
Country |
| 1 |
John |
Doe |
USA |
| 2 |
Jane |
Smith |
UK |
| 3 |
Michael |
Brown |
Canada |
| 4 |
Emily |
Jones |
USA |
Consider The Previous Table Customer
SELECT DISTINCT Country FROM Customer;
OutPut
As You can see In the Example That we Specified The Column Country
from Table Customer and it only Retured the unique values the
Country Containing ( Redundant Data Won't be Shown )
SQL WHERE Clause
The WHERE statement in SQL is used to filter records that meet a specific condition. It is commonly used
with SELECT, UPDATE, DELETE, and other SQL commands to retrieve or modify rows based on the condition
specified.
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example
Consider a table named Customers with the following data:
| Customer ID |
First Name |
Last Name |
Country |
| 1 |
John |
Doe |
USA |
| 2 |
Jane |
Smith |
UK |
| 3 |
Michael |
Brown |
Canada |
| 4 |
Emily |
Jones |
USA |
To select customers from the USA, you can use the following SQL query:
SELECT * FROM Customers
WHERE Country = 'USA';
Output
| Customer ID |
First Name |
Last Name |
Country |
| 1 |
John |
Doe |
USA |
| 4 |
Emily |
Jones |
USA |
SQL ORDER BY Clause
The ORDER BY statement in SQL is used to sort the result set of a query by one or more columns. By default,
the ORDER BY clause sorts the records in ascending order. You can specify descending order by using the DESC
keyword.
Syntax
SELECT column1, column2, ...
FROM table_name
ORDER BY column1 [ASC|DESC], column2 [ASC|DESC], ...;
Example
Consider a table named Customers with the following data:
| Customer ID |
First Name |
Last Name |
Country |
| 1 |
John |
Doe |
USA |
| 2 |
Jane |
Smith |
UK |
| 3 |
Michael |
Brown |
Canada |
| 4 |
Emily |
Jones |
USA |
To select all customers and order them by their last names in ascending order, you can use the following
SQL query:
SELECT * FROM Customers
ORDER BY Last_Name ASC;
Output
| Customer ID |
First Name |
Last Name |
Country |
| 1 |
John |
Doe |
USA |
| 4 |
Emily |
Jones |
USA |
| 2 |
Jane |
Smith |
UK |
| 3 |
Michael |
Brown |
Canada |
SQL AND Clause
The AND operator in SQL is used to combine multiple conditions in a WHERE clause. It allows you to filter
records that meet all specified conditions. If any of the conditions separated by AND are false, the entire
condition evaluates to false.
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND ...;
Example
Consider a table named Customers with the following data:
| Customer ID |
First Name |
Last Name |
Country |
Age |
| 1 |
John |
Doe |
USA |
30 |
| 2 |
Jane |
Smith |
UK |
25 |
| 3 |
Michael |
Brown |
Canada |
35 |
| 4 |
Emily |
Jones |
USA |
28 |
To select customers from the USA who are over 25 years old, you can use the following SQL query:
SELECT * FROM Customers
WHERE Country = 'USA' AND Age > 25;
Output
| Customer ID |
First Name |
Last Name |
Country |
Age |
| 1 |
John |
Doe |
USA |
30 |
SQL OR Clause
The OR operator in SQL is used to combine multiple conditions in a WHERE clause. It allows you to filter
records that meet at least one of the specified conditions. If any of the conditions separated by OR are
true, the entire condition evaluates to true.
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR ...;
Example
Consider a table named Customers with the following data:
| Customer ID |
First Name |
Last Name |
Country |
Age |
| 1 |
John |
Doe |
USA |
30 |
| 2 |
Jane |
Smith |
UK |
25 |
| 3 |
Michael |
Brown |
Canada |
35 |
| 4 |
Emily |
Jones |
USA |
28 |
To select customers from either the USA or Canada, you can use the following SQL query:
SELECT * FROM Customers
WHERE Country = 'USA' OR Country = 'Canada';
Output
| Customer ID |
First Name |
Last Name |
Country |
Age |
| 1 |
John |
Doe |
USA |
30 |
| 3 |
Michael |
Brown |
Canada |
35 |
| 4 |
Emily |
Jones |
USA |
28 |
SQL INSERT INTO Clause
The INSERT INTO statement in SQL is used to add new records to a table. You can specify the columns and the
values you want to insert. If you do not specify the columns, the values must match the order of the columns
in the table.
Syntax
INSERT INTO table_name (column1, column2, ...)
VALUES (value1, value2, ...);
Example
Consider a table named Customers with the following structure:
| Customer ID |
First Name |
Last Name |
Country |
Age |
| 1 |
John |
Doe |
USA |
30 |
| 2 |
Jane |
Smith |
UK |
25 |
To insert a new customer into the Customers table, you can use the following SQL query:
INSERT INTO Customers (First_Name, Last_Name, Country, Age)
VALUES ('Emily', 'Jones', 'USA', 28);
Output
After executing the above query, the Customers table will have the following data:
| Customer ID |
First Name |
Last Name |
Country |
Age |
| 1 |
John |
Doe |
USA |
30 |
| 2 |
Jane |
Smith |
UK |
25 |
| 3 |
Emily |
Jones |
USA |
28 |
SQL NULL Values
In SQL, NULL represents a missing or undefined value. It is used to indicate that a data value does not
exist in the database. When working with NULL values, special care must be taken, especially when filtering
results in queries.
Syntax
SELECT column1, column2, ...
FROM table_name
WHERE column_name IS NULL;
Example
Consider a table named Customers with the following data:
| Customer ID |
First Name |
Last Name |
Country |
Age |
Email |
| 1 |
John |
Doe |
USA |
30 |
john.doe@example.com |
| 2 |
Jane |
Smith |
UK |
25 |
NULL |
| 3 |
Michael |
Brown |
Canada |
35 |
michael.brown@example.com |
| 4 |
Emily |
Jones |
USA |
28 |
NULL |
To select customers who do not have an email address, you can use the following SQL query:
SELECT * FROM Customers
WHERE Email IS NULL;
Output
| Customer ID |
First Name |
Last Name |
Country |
Age |
Email |
| 2 |
Jane |
Smith |
UK |
25 |
NULL |
| 4 |
Emily |
Jones |
USA |
28 |
NULL |
SQL GROUP BY Clause
The GROUP BY statement in SQL is used to arrange identical data into groups. This is often used in
conjunction with aggregate functions like COUNT, SUM, AVG, MAX, or MIN to perform calculations on each group
of data.
Syntax
SELECT column1, aggregate_function(column2)
FROM table_name
WHERE condition
GROUP BY column1;
Example
Consider a table named Orders with the following data:
| Order ID |
Customer ID |
Amount |
Order Date |
| 1 |
1 |
100 |
2023-01-01 |
| 2 |
2 |
150 |
2023-01-02 |
| 3 |
1 |
200 |
2023-01-03 |
| 4 |
3 |
250 |
2023-01-04 |
To calculate the total amount spent by each customer, you can use the following SQL query:
SELECT Customer_ID, SUM(Amount) AS Total_Spent
FROM Orders
GROUP BY Customer_ID;
Output
| Customer ID |
Total Spent |
| 1 |
300 |
| 2 |
150 |
| 3 |
250 |
SQL HAVING Clause
The HAVING clause in SQL is used to filter records that work on summarized group data. It is often used in
conjunction with the GROUP BY clause to apply conditions to the grouped records.
Syntax
SELECT column1, aggregate_function(column2)
FROM table_name
GROUP BY column1
HAVING condition;
Example
Consider a table named Orders with the following data:
| Order ID |
Customer ID |
Amount |
| 1 |
1 |
100 |
| 2 |
2 |
150 |
| 3 |
1 |
200 |
| 4 |
3 |
250 |
To find customers who have spent more than $200 in total, you can use the following SQL query:
SELECT Customer_ID, SUM(Amount) AS Total_Spent
FROM Orders
GROUP BY Customer_ID
HAVING SUM(Amount) > 200;
Output
| Customer ID |
Total Spent |
| 1 |
300 |
SQL Joins
SQL Joins are used to combine rows from two or more tables based on a related column between them. Joins
allow you to retrieve data from multiple tables in a single query, which is essential for relational
databases.
Types of Joins
- INNER JOIN: Returns records that have matching values in both tables.
- LEFT JOIN (or LEFT OUTER JOIN): Returns all records from the left table and the
matched records from the right table. If there is no match, NULL values are returned for columns from
the right table.
- RIGHT JOIN (or RIGHT OUTER JOIN): Returns all records from the right table and the
matched records from the left table. If there is no match, NULL values are returned for columns from the
left table.
- FULL JOIN (or FULL OUTER JOIN): Returns all records when there is a match in either
left or right table records. If there is no match, NULL values are returned for non-matching columns
from both tables.
INNER JOIN Example
Consider two tables: Customers and Orders.
Customers Table:
| Customer ID |
First Name |
Last Name |
| 1 |
John |
Doe |
| 2 |
Jane |
Smith |
Orders Table:
| Order ID |
Customer ID |
Product |
| 101 |
1 |
Widget |
| 102 |
1 |
Gadget |
| 103 |
2 |
Thingamajig |
To select all customers along with their orders, you can use the following SQL query with an INNER JOIN:
SELECT Customers.First_Name, Customers.Last_Name, Orders.Product
FROM Customers
INNER JOIN Orders ON Customers.Customer_ID = Orders.Customer_ID;
Output
| First Name |
Last Name |
Product |
| John |
Doe |
Widget |
| John |
Doe |
Gadget |
| Jane |
Smith |
Thingamajig |
LEFT JOIN Example
To select all customers and their orders, including customers without orders, you can use the following
SQL query with a LEFT JOIN:
SELECT Customers.First_Name, Customers.Last_Name, Orders.Product
FROM Customers
LEFT JOIN Orders ON Customers.Customer_ID = Orders.Customer_ID;
Output
| First Name |
Last Name |
Product |
| John |
Doe |
Widget |
| John |
Doe |
Gadget |
| Jane |
Smith |
Thingamajig |
| Bob |
Johnson |
NULL |
RIGHT JOIN Example
To select all orders and their corresponding customers, including orders without customers, you can use
the following SQL query with a RIGHT JOIN:
SELECT Customers.First_Name, Customers.Last_Name, Orders.Product
FROM Customers
RIGHT JOIN Orders ON Customers.Customer_ID = Orders.Customer_ID;
Output
| First Name |
Last Name |
Product |
| John |
Doe |
Widget |
| John |
Doe |
Gadget |
| Jane |
Smith |
Thingamajig |
| NULL |
NULL |
Unordered Item |
FULL OUTER JOIN Example
To select all customers and all orders, including customers without orders and orders without customers,
you can use the following SQL query with a FULL OUTER JOIN:
SELECT Customers.First_Name, Customers.Last_Name, Orders.Product
FROM Customers
FULL OUTER JOIN Orders ON Customers.Customer_ID = Orders.Customer_ID;
Output
| First Name |
Last Name |
Product |
| John |
Doe |
Widget |
| John |
Doe |
Gadget |
| Jane |
Smith |
Thingamajig |
| NULL |
NULL |
Unordered Item |
| Bob |
Johnson |
NULL |
SQL Aggregate Functions
SQL Aggregate Functions are used to perform calculations on a set of values and return a single value. These
functions are often used in conjunction with the GROUP BY clause to summarize data. Common aggregate
functions include COUNT, SUM, AVG, MAX, and MIN.
Common Aggregate Functions
- COUNT: Returns the number of rows that match a specified criterion.
- SUM: Returns the total sum of a numeric column.
- AVG: Returns the average value of a numeric column.
- MAX: Returns the maximum value in a set.
- MIN: Returns the minimum value in a set.
Example
Consider a table named Sales with the following data:
| Sale ID |
Product |
Amount |
Quantity |
| 1 |
Widget |
100 |
2 |
| 2 |
Gadget |
150 |
1 |
| 3 |
Thingamajig |
200 |
3 |
| 4 |
Widget |
100 |
1 |
To find the total sales amount and the average quantity sold, you can use the following SQL query:
SELECT SUM(Amount) AS Total_Sales, AVG(Quantity) AS Average_Quantity
FROM Sales;
Output
| Total Sales |
Average Quantity |
| 550 |
1.75 |
In this example, the total sales amount is calculated as $550, and the average quantity sold is 1.75.
SQL Functions
SQL functions are predefined operations that allow you to perform calculations, manipulate data, and return
specific results from the database. They are essential for data analysis and reporting in SQL queries.
Functions can be categorized into aggregate functions, scalar functions, string functions, and date
functions, each serving different purposes in data handling.
Syntax
-- Aggregate Function Example
SELECT AGGREGATE_FUNCTION(column_name)
FROM table_name
WHERE condition;
-- Scalar Function Example
SELECT SCALAR_FUNCTION(column_name)
FROM table_name;
Example
Consider a table named Sales with the following data:
| Sale ID |
Product |
Amount |
Quantity |
| 1 |
Widget |
100 |
2 |
| 2 |
Gadget |
150 |
1 |
| 3 |
Thingamajig |
200 |
3 |
| 4 |
Widget |
100 |
1 |
To calculate the total sales amount and the average quantity sold, you can use the following SQL query:
SELECT SUM(Amount) AS Total_Sales, AVG(Quantity) AS Average_Quantity
FROM Sales;
Output
| Total Sales |
Average Quantity |
| 550 |
1.75 |
In this example, the total sales amount is calculated as $550, and the average quantity sold is 1.75.
SQL Indexes
An index in SQL is a database object that improves the speed of data retrieval operations on a table at the
cost of additional space and slower writes. Indexes are used to quickly locate and access the data in a
database table without having to search every row. They can be created on one or more columns of a table and
are essential for optimizing query performance.
Syntax
CREATE INDEX index_name
ON table_name (column1, column2, ...);
Example
Consider a table named Employees with the following data:
| Employee ID |
First Name |
Last Name |
Department |
| 1 |
John |
Doe |
HR |
| 2 |
Jane |
Smith |
IT |
| 3 |
Michael |
Brown |
Finance |
| 4 |
Emily |
Jones |
IT |
To create an index on the Last Name column of the Employees table, you
can use the following SQL query:
CREATE INDEX idx_last_name
ON Employees (Last_Name);
Output
After executing the above query, an index named idx_last_name will be created on the
Last Name column, which can improve the performance of queries that filter or sort by
this column.
SQL Constraints
SQL constraints are rules applied to columns in a table to ensure the integrity and validity of the data.
They help enforce data integrity by restricting the type of data that can be stored in a table. Common types
of constraints include PRIMARY KEY, FOREIGN KEY, UNIQUE, NOT NULL, and CHECK constraints, each serving a
specific purpose in maintaining data quality and relationships.
Syntax
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
...
CONSTRAINT constraint_name PRIMARY KEY (column_name),
CONSTRAINT constraint_name FOREIGN KEY (column_name) REFERENCES other_table (column_name)
);
Example
Consider a table named Orders that references a Customers table:
| Order ID |
Customer ID |
Order Date |
Amount |
| 1 |
101 |
2023-01-15 |
250.00 |
| 2 |
102 |
2023-01-16 |
150.00 |
To create the Orders table with constraints, you can use the following SQL query:
CREATE TABLE Orders (
Order_ID INT PRIMARY KEY,
Customer_ID INT,
Order_Date DATE,
Amount DECIMAL(10, 2),
CONSTRAINT fk_customer
FOREIGN KEY (Customer_ID) REFERENCES Customers(Customer_ID)
ON DELETE CASCADE
);
Output
In this example, the Order_ID is defined as the PRIMARY KEY, ensuring that each order is
uniquely identifiable. The Customer_ID column is defined as a FOREIGN KEY, establishing a
relationship with the Customers table. The ON DELETE CASCADE option
ensures that if a customer is deleted, all their associated orders will also be deleted automatically.
SQL Transactions
A transaction in SQL is a sequence of one or more SQL operations that are executed as a single unit of work.
Transactions ensure data integrity by allowing you to group multiple operations into a single logical unit.
If any operation within the transaction fails, the entire transaction can be rolled back, ensuring that the
database remains in a consistent state. The key properties of transactions are encapsulated in the ACID
principles: Atomicity, Consistency, Isolation, and Durability.
Syntax
BEGIN TRANSACTION;
-- SQL operations (INSERT, UPDATE, DELETE)
-- Example:
INSERT INTO table_name (column1, column2) VALUES (value1, value2);
COMMIT; -- Save changes
-- or
ROLLBACK; -- Undo changes if an error occurs
Example
Consider a banking application where you want to transfer funds from one account to another:
| Account ID |
Account Holder |
Balance |
| 1 |
John Doe |
1000.00 |
| 2 |
Jane Smith |
500.00 |
To transfer $200 from John Doe's account to Jane Smith's account, you can use the following SQL
transaction:
BEGIN TRANSACTION;
UPDATE Accounts
SET Balance = Balance - 200
WHERE Account_ID = 1;
UPDATE Accounts
SET Balance = Balance + 200
WHERE Account_ID = 2;
COMMIT; -- Save changes
Output
In this example, the transaction ensures that both updates (debit from John Doe's account and credit to
Jane Smith's account) are executed together. If either update fails, you can issue a
ROLLBACK command to undo any changes made during the transaction, keeping the account
balances consistent.