Database & SQL — Part(3) SQL

Hello everyone reading here, I am happy that you are here. I hope you are well and have a beautiful day ♥ I think you are here now after reading the first part & second part, and here to keep learning.

What is SQL?

— A programming language dedicated to managing and dealing with databases to enable the user to review, analyze, modify, and delete data using some commands. SQL is comprised of five foundational elements:

→DDL (Data Definition Language) includes Create, Drop, Alter, and Truncate.

→DML (Data Manipulation Language) include Insert, Update, Delete.

→DCL (Data Control Language) includes Grant, Revoke.

→TCL (Transaction Control Language) includes Commit, Rollback, and Save point.

→DOL (Data Query Language) includes Select.

Over-all

  • SQL stands for Structured Query Language

  • SQL lets you access and manipulate databases

  • SQL can execute queries and retrieve data from a database

  • SQL can insert, update, and delete records from a database

  • SQL can create new databases and new tables in a database

  • SQL can create stored procedures and views in a database

  • SQL can set permissions on tables, procedures, and views.

The first thing we will imagine is a scenario that will be like the following. We will create a database called Company

CREATE DATABASE :

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

CREATE DATABASE databasename;
CREATE DATABASE Company;

DROP DATABASE:

— The DROP DATABASE statement is used to drop an existing SQL database.

▪ DROP DATABASE databasename;

Then we will start creating the table and specify the primary key and foreign key.

CREATE TABLE:

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

▪ CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);
CREATE TABLE Persons (
PersonID int NOT NULL,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (PersonID)

);

We will make another table to know how to connect them with the primary key and foreign key.

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

DROP TABLE:

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

 DROP TABLE table_name;

TRUNCATE TABLE:

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

TRUNCATE TABLE table_name;

After that, we will add data

INSERT INTO:

— Insert new data into a database followed by VALUES containing the data you want to insert.

Note the use “,” here.

INSERT INTO Persons (PersonID, LastName, FirstName, Address, City) 
VALUES (1, 'Marlin', 'Nemo', 'P. Sherman, 42 Wallaby Way, Sydney', ' wallaby');

Output:

If we want to add more than one row.

Note the use “,” here.

INSERT INTO Persons (PersonID, LastName, FirstName, Address, City) 
VALUES 
    (1, 'Marlin', 'Nemo', 'P. Sherman, 42 Wallaby Way, Sydney', 'wallaby'), 
    (2, 'Dani', 'Dory', 'P. Sherman, 42 Wallaby Way, Sydney', 'wallaby');

Output:

UPDATE:

— The UPDATE statement is used to modify the existing records in a table followed by “SET” you list the columns you want to update.

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
UPDATE Persons
SET PersonID = 3, LastName ="bagi"
WHERE PersonID = 1;

output:

DELETE:

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

DELETE FROM table_name WHERE condition;
DELETE FROM Persons WHERE PersonID = 2;

output

SELECT:

— used to retrieve data from one or more tables in a database.

SELECT column1, column2, ...
FROM table_name
WHERE condition;

Of course, we add data to the table to explain the example.

SELECT PersonID, Address
FROM Persons
WHERE FirstName = 'Ahmed' OR FirstName = 'Nemo';

output:

If you want to select all the fields available in the table, use

SELECT * FROM table_name;

SELECT DISTINCT:

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

SELECT DISTINCT column1, column2, ...
FROM table_name;

Additional SQL Features:

Beyond the basics, SQL offers a rich set of functionalities:

  • Aggregate functions: Calculate sums, averages, counts, and more (e.g., SUM, AVG, COUNT).

  • Grouping: Organize data into groups and summarize it (e.g., GROUP BY).

  • Subqueries: Embed queries within other queries for complex data retrieval.

  • Logical operators: Combine conditions with AND, OR, and NOT.

Putting It All Together:

These are just a few building blocks of SQL. As you practice and explore, you’ll unlock its true potential for managing and extracting valuable insights from your data.

AND, OR and NOT Operators:

logical operators used to combine multiple conditions in the WHERE clause of a SELECT, UPDATE, DELETE, or INSERT statement. These operators allow you to build more complex conditions for filtering data from the database.

AND

SELECT column1, column2, ...
FROM table_name
WHERE condition1 AND condition2 AND condition3 ...;
SELECT PersonID, Address
FROM Persons
WHERE FirstName = 'Ahmed' AND LastName = 'wagdi';

output:

Note that: don’t write two condition conflict with each other

like first name =’Ahmed’ and first name=’Nemo’

OR

SELECT column1, column2, ...
FROM table_name
WHERE condition1 OR condition2 OR condition3 ...;

NOT

SELECT column1, column2, ...
FROM table_name
WHERE NOT condition;
SELECT PersonID, Address
FROM Persons
WHERE NOT FirstName = 'Ahmed';

output:

LIMIT & OFFSET Clauses

used in SQL queries to control the number of rows returned by a query and to skip a certain number of rows, respectively.

In other words, like limit from number to number, after offset comes the maximum row number that can be retrieved.

SELECT * FROM table_name
LIMIT 10 OFFSET 20;

ORDER BY:

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

SELECT column1, column2, ...
FROM table_name
ORDER BY column1, column2, ... ASC|DESC;
SELECT LastName, FirstName, Address
FROM Persons
ORDER BY PersonID DESC;

Output:

Additional SQL Features:

Beyond the basics, SQL offers a rich set of functionalities:

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

▪ SELECT MIN(column_name)
FROM table_name;

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

SELECT MAX(column_name)
FROM table_name;

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

SELECT COUNT(column_name)
FROM table_name;
SELECT COUNT(*)
FROM Persons
WHERE City = 'wallaby';

output:

Note that : here \ this meaning number of rows that city=wallaby*

SELECT COUNT(City)
FROM Persons;

Note that: here city meaning number of rows that coulm of city not null.

Output:

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

SELECT AVG(column_name)
FROM table_name;

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

SELECT SUM(column_name)
FROM table_name;

GROUP BY

The GROUP BY statement groups rows that have the same values into summary rows, like “find the number of customers in each country”.

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s);

HAVING Clause

The HAVING clause was added to SQL because the WHERE keyword cannot be used with aggregate functions.

SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);

The following SQL statement lists the number of customers in each country. Only include countries with more than 5 customers:

SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;

Quick tip

→The Commands in SQL are not Case-sensitive, but the column names are case-sensitive.

→An SQL statement should end with a semicolon, although many database systems (DBMS) do not put “;”.

Comments

/* 
  this is a
  multi-line comment
*/


-- this is a single line comment

-- SELECT COUNT(CustomerID), Country
FROM Customers;

→We can’t use “=” with NULL when comparing column’s value. Instead, use the operators ‘IS NULL’, and, ‘IS NOT NULL’.

→ NULL is not a value, it’s a state of no value, not zero, not an empty string.

SELECT * FROM Persons 
WHERE lastName = 'Marlin' OR lastName IS NULL;

JOIN:

A JOIN clause is used to combine rows from two or more tables, based on a related column between them.

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

INNER JOIN:

SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;

Note: JOIN and INNER JOIN will return the same result.

LEFT JOIN:

The LEFT JOIN keyword returns all records from the left table (table1), and the matching records from the right table (table2). The result is 0 records from the right side if there is no match).

SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;

FULL JOIN:

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

SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;

Note: FULL OUTER JOIN and FULL JOIN are the same.

wrapping up

Finally, today we finished Most of the SQL commands, but not all of them. There are seas of SQL commands. We took some examples that I hope will be useful. If you want the application, you have many options, such as Microsoft SQL Server, but I used XAMPP.

In case you encounter any problem with xampp.

I hope it is useful, easy, and simple for you.

References:

W3S

That’s it, we’re done. God make your dreams come true ♥

Facebook

LinkedIn