SQL
SQL
SQL
BASICS OF SQL
SQL - STRUCTURED QUERY LANGUAGE
SQL is a standard language for storing, manipulating and retrieving data in databases.
SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert records in a database
SQL can update records in a database
SQL can delete records from a database
SQL can create new databases
SQL can create new tables in a database
SQL can create stored procedures in a database
SQL can create views in a database
SQL can set permissions on tables, procedures, and views
SQL is used while creating websites to integrate the database with the website
SQL Tools:
Microsoft SQL
PostgreSQL
My SQL etc.,
------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
DATABASE
Database is the collection of data related to each other in the forms of table so that we will
access and manipulate data from the database while creating websites
Database Management System DBMS is the software designed to store, organize, and
manage data efficiently.
The database is a collection of interconnected data.
The management system ensures proper handling of data.
------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
TABLES
Table are the intersection of rows and columns that a database has within it and with those
data the sql queries access the database
DATA-TYPES
SQL data types are used to define the type of data that can be stored in each column of a
table. Here's a breakdown of the common SQL data types:
a. INTEGER (INT):
SAMPLE CODE:
CREATE TABLE Table_name (
Name INT);
Similarly, SMALLINT & BIGINT are used to store small and big integer values
2. CHARACTER and STRING DATATYPES: Used to stores letters, words and texts even
OUTPUT:
EventID | EventDate | EventTime | EventDateTime | CreatedAt
---------------------------------------------------------------------------
1 | 2024-10-23 | 14:30:00 | 2024-10-23 14:30:00 | 2024-10-23 14:35:50
2 | 2024-10-24 | 09:00:00 | 2024-10-24 09:00:00 | 2024-10-24 09:05:10
5. BINARY DATATYPE: Used to store binary data like files, images, or encrypted data.
a. BINARY(n): Stores fixed-length binary data.
b. VARBINARY(n): Stores variable-length binary data.
C. BLOB: Stores large binary objects (e.g., images or files).
6. OTHER DATATYPES:
a. ENUM: A string object with a value chosen from a list of allowed values.
b. SET: Similar to ENUM, but allows multiple values from the list.
c. POINT: Represents a single point in a 2D space.
d. LINESTRING: Represents a line defined by two or more points.
e. POLYGON: Represents a polygon defined by multiple points.
------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
SQL CONSTRAINTS
a. PRIMARY KEY: Uniqueness
Ensures each row is unique and non-null.
d. UNIQUE: Distinct
Guarantees all values in a column are distinct.
e. CHECK: Validation
Validates that data meets a specific condition.
f. DEFAULT: Pre-set
Assigns a default value if none is provided
g. INDEX: Fast-access
Speeds up retrieval of rows by creating an index on columns.
SAMPLE CODE:
--------------------------------------------------------------------------------------------------------------
INDEX
Index is used to locate or extract the data from the table
Example:
CREATE INDEX idx_Lastname ON Employee_table(Lastname):
This will sort the data based on the lastname when we give the input
-----------------------------------------------------------------------------------------------------------------
COMMAND STATEMENTS
SAMPLE CODE:
CREATE TABLE Departments (Dept_name);
ALTER TABLE Employees DROP COLUMN DepartmentID;
2.DML
DML commands are used to manipulate the data within the tables.
SELECT - Retrieves certain records from one or more tables.
INSERT - Creates a record.
UPDATE - Modifies records.
DELETE - Deletes records.
SAMPLE CODE:
INSERT INTO Departments (DepartmentID, DepartmentName) VALUES
(1, 'Human Resources'),
(2, 'Finance'),
(3, 'IT');
UPDATE Employees
SET Salary = 65000.00
WHERE EmployeeID = 2;
DELETE FROM Employees
WHERE EmployeeID = 1;
3.DQL
A subset of SQL used to retrieve and query data from a database, primarily through the
SELECT statement.
SELECT - Retrieves certain records from one or more tables
JOIN: Combines rows from two or more tables based on a related column between them.
WHERE: Filters records that meet a specified condition.
AVG (): An aggregate function that calculates the average of a specified column.
SAMPLE CODE:
SELECT * FROM Employees;
SELECT FirstName, LastName FROM Employees;
SELECT * FROM Departments WHERE DepartmentName = 'IT';
SELECT E.FirstName, E.LastName, D.DepartmentName FROM Employees JOIN
Departments D ON E.DepartmentID = D.DepartmentID;
SELECT AVG(Salary) AS AverageSalary FROM Employees;
4.DCL
DCL commands are used to control access to data in the database.
GRANT - Gives a privilege to the user.
REVOKE - Takes back privileges granted by the user.
SAMPLE CODE:
GRANT SELECT, INSERT ON Employees TO user_name;
REVOKE INSERT ON Employees FROM user_name;
5.TCL
TCL commands manage transactions in a database.
COMMIT: Saves all changes made in the current transaction.
ROLLBACK: Undoes changes made in the current transaction.
SAMPLE CODE:
COMMIT;
ROLLBACK;
-----------------------------------------------------------------------------------------------------------------
STRING FUNCTION
String functions are used to manipulate and process string datatypes
1.LENGTH (): Returns the length of a string.
2. UPPER(): Converts a string to uppercase.
3. LOWER(): Converts a string to lowercase.
4. CONCAT(): Combines two or more strings.
5. SUBSTRING(): Extracts a portion of a string.
6. TRIM(): Removes leading and trailing spaces from a string.
7. REPLACE(): Replaces occurrences of a substring within a string.
8. CHARINDEX(): Returns the position of a substring in a string (SQL Server).
SAMPLE CODE:
LENGTH(FirstName) FROM Employees
UPPER(FirstName) FROM Employees
LOWER(LastName) FROM Employees
CONCAT(FirstName, ' ', LastName) AS FullName FROM Employees
SUBSTRING(Email, 1, 5) FROM Employees
TRIM(FirstName) FROM Employees
REPLACE(Email, '@example.com', '@newdomain.com') FROM Employees
CHARINDEX('a', FirstName) FROM Employees
------------------------------------------------------------------------------------------------------------------
AGGREGATE FUNCTIONS
Used to perform calculations on a set of values and return a single value.
They are commonly used in conjunction with the GROUP BY clause to group records based
on one or more columns
------------------------------------------------------------------------------------------------------------------
DATE FUNCTIONS
1. CURRENT_DATE: Returns the current date.
SELECT CURRENT_DATE;
------------------------------------------------------------------------------------------------------------------
JOINS
Used to combine rows from two or more tables based on a related column between them.
1. INNER JOIN: Returns only the rows that have matching values in both tables
SELECT Employees.FirstName, Departments.DepartmentName
FROM Employees
INNER JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;
2. LEFT JOIN (LEFT OUTER JOIN): Returns all rows from the left table and the matched
rows from the right table. If no match is found, NULL values are returned for columns from
the right table.
SELECT Employees.FirstName, Departments.DepartmentName
FROM Employees
LEFT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;
3. RIGHT JOIN (RIGHT OUTER JOIN): Returns all rows from the right table and the matched
rows from the left table. If no match is found, NULL values are returned for columns from
the left table.
SELECT Employees.FirstName, Departments.DepartmentName
FROM Employees
RIGHT JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;
4. FULL JOIN (FULL OUTER JOIN): Returns all rows when there is a match in either left or
right table records. If no match is found, NULL values are returned for columns from the
table that does not have a match.
SELECT Employees.FirstName, Departments.DepartmentName
FROM Employees
FULL JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID;
5. CROSS JOIN: Returns the Cartesian product of both tables, meaning it returns all
possible combinations of rows from both tables.
SELECT Employees.FirstName, Departments.DepartmentName
FROM Employees
CROSS JOIN Departments;
-----------------------------------------------------------------------------------------------------------------
SUB QUERIES
Sub queries are used to retrieve data that will be used in the main query.
1. Subquery in the SELECT Clause: This retrieves data based on a calculation from
another table.
SELECT FirstName, LastName, (SELECT COUNT(*)
FROM Employees WHERE DepartmentID = 1) AS Dept1EmployeeCount
FROM Employees;
2. Subquery in the WHERE Clause: This filters records based on a condition derived from
another query.
SELECT FirstName, LastName
FROM Employees
WHERE DepartmentID IN (SELECT DepartmentID FROM Departments WHERE
DepartmentName = 'IT');
3. Subquery in the FROM Clause: This allows the use of a subquery as a table in the main
query.
4. Correlated Subquery: This references a column from the outer query and runs once for
each row processed by the outer query.
------------------------------------------------------------------------------------------------------------------