0% found this document useful (0 votes)
4 views

SQL

The document provides a comprehensive overview of SQL, including its basics, syntax, and various commands for managing databases. It covers essential topics such as data types, constraints, command categories (DDL, DML, DQL, DCL, TCL), string and aggregate functions, joins, and subqueries. Additionally, it includes sample code for practical understanding and implementation of SQL operations.

Uploaded by

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

SQL

The document provides a comprehensive overview of SQL, including its basics, syntax, and various commands for managing databases. It covers essential topics such as data types, constraints, command categories (DDL, DML, DQL, DCL, TCL), string and aggregate functions, joins, and subqueries. Additionally, it includes sample code for practical understanding and implementation of SQL operations.

Uploaded by

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

DATE – OCT-25, 2024 DAY - FRIDAY

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

Basic SQL syntax


SELECT column1, column2
FROM table_name
WHERE condition;
SELECT: Specifies which columns to retrieve.
FROM: Indicates the table to retrieve data from.
WHERE: Adds conditions to filter the results.

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.

CREATE DATABASE Database_name;

------------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------

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

To create an employee table:

CREATE TABLE Employees (


EmployeeID INT PRIMARY KEY,
FirstName VARCHAR (50),
LastName VARCHAR (50),
Department VARCHAR (50),
Hire Date DATE,
Salary DECIMAL (10, 2)
);

With these table the queries can be executed


------------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------

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:

These datatypes are declared in the queries


1. NUMERIC DATA TYPES - Used to store numbers

a. INTEGER (INT):
SAMPLE CODE:
CREATE TABLE Table_name (
Name INT);
Similarly, SMALLINT & BIGINT are used to store small and big integer values

b. DECIMAL / NUMERIC: Stores fixed point numbers


CREATE TABLE Table_name (
Weight DECIMAL (150,10));

c. FLOAT: Stores approximate values in float


CREATE TABLE Table_name (
Weight FLOAT);
Similarly, DOUBLE and FLOAT are same but DOUBLE can store more values than the
FLOAT can hold

2. CHARACTER and STRING DATATYPES: Used to stores letters, words and texts even

a. CHARACTER (CHAR): Store character of fixed length


b. VARIABLE CHARACTER (VARCHAR): Stores character of maximum length
c. TEXT: Stores lines or even paragraphs
SAMPLE CODE:
CREATE TABEL Table_name (
Name VARCHAR (100),
Office name CHAR (10),
Employment history TEXT);
3. DATE AND TIME DATATYPES: Used for storing data in different formats

a. DATE: Used to store date in [YYYY:MM:DD] format


b. TIME: Time is used to store time in [HH:MM: SS] format
c. DATETIME: Used to store both date and time [YYYY:MM:SS HH:MM:SS]
d. TIMESTAMP: Similar to DATETIME but also stores Time zone Information
SAMPLE CODE:
CREATE TABLE EventLog (
EventID INT PRIMARY KEY,
EventDate DATE,
EventTime TIME,
EventDateTime DATETIME,
CreatedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO EventLog (EventID, EventDate, EventTime, EventDateTime)
VALUES
(1, '2024-10-23', '14:30:00', '2024-10-23 14:30:00'),
(2, '2024-10-24', '09:00:00', '2024-10-24 09:00:00');
SELECT EventID, EventDate, EventTime, EventDateTime, CreatedAt
FROM EventLog;

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

4.BOOLEAN DATA TYPES:


a. BOOLEAN: Used to store True or False values
(represented as True-1; False-0)
SAMPLE CODE:
CREATE TABLE EmployeeStatus (
EmployeeID INT PRIMARY KEY, -- Integer primary key
EmployeeName VARCHAR(50), -- Variable-length string is Active
BOOLEAN -- Boolean field to indicate active status);

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.

b. FOREIGN KEY: Reference


Links records between tables, enforcing referential integrity.

c. NOT NULL: Mandatory


Ensures a column cannot contain NULL values.

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:

CREATE TABLE Departments (


DepartmentID INT PRIMARY KEY,
DepartmentName VARCHAR(50) NOT NULL UNIQUE );

CREATE TABLE Employees (


EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50) NOT NULL,
Email VARCHAR(100) UNIQUE,
HireDate DATE NOT NULL DEFAULT CURRENT_DATE,
Salary DECIMAL(10, 2) CHECK (Salary > 0),
DepartmentID INT,
FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID)
);
CREATE INDEX idx_lastname ON Employees (LastName);

--------------------------------------------------------------------------------------------------------------
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

SQL Command statements are categorized into 5 types


1.DDL
DDL commands are used to define and modify database structures
CREATE - Creates a new table, a view of a table, or other object in the database.
ALTER - Modifies an existing database object, such as a table
DROP - Deletes an entire table, a view of a table, or other objects in the database

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

1. COUNT(): Returns the number of rows that match a specified condition.


SELECT COUNT(*) FROM Employees;

2. SUM(): Returns the total sum of a numeric column.


SELECT SUM(Salary) FROM Employees;

3. AVG(): Returns the average value of a numeric column.


SELECT AVG(Salary) FROM Employees:

4. MAX(): Returns the maximum value of a column.


SELECT MAX(Salary) FROM Employees;

5. MIN(): Returns the minimum value of a column.


SELECT MIN(Salary) FROM Employees;

------------------------------------------------------------------------------------------------------------------
DATE FUNCTIONS
1. CURRENT_DATE: Returns the current date.
SELECT CURRENT_DATE;

2. NOW(): Returns the current date and time.


SELECT NOW();
3. DATE(): Extracts the date part from a datetime expression.
SELECT DATE(NOW());

4. YEAR(): Returns the year from a date.


SELECT YEAR(HireDate) FROM Employees;

5. MONTH(): Returns the month from a date.


SELECT MONTH(HireDate) FROM Employees;

6. DAY(): Returns the day of the month from a date.


SELECT DAY(HireDate) FROM Employees;

7. DATEDIFF(): Returns the difference between two dates.


SELECT DATEDIFF(CURRENT_DATE, HireDate) FROM Employees;

8. DATE_ADD(): Adds a specified time interval to a date.


SELECT DATE_ADD(HireDate, INTERVAL 1 YEAR) FROM Employees;

9. DATE_SUB(): Subtracts a specified time interval from a date.


SELECT DATE_SUB(HireDate, INTERVAL 1 MONTH) FROM Employees;

10. FORMAT(): Formats a date value based on a specified format.


SELECT FORMAT(HireDate, 'YYYY-MM-DD') FROM Employees;

------------------------------------------------------------------------------------------------------------------

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.

SELECT AVG(Salary) AS AverageSalary

FROM (SELECT Salary

FROM Employees WHERE DepartmentID = 1) AS Dept1Salaries;

4. Correlated Subquery: This references a column from the outer query and runs once for
each row processed by the outer query.

SELECT FirstName, LastName

FROM Employees E WHERE Salary > (SELECT AVG(Salary)

FROM Employees WHERE DepartmentID = E.DepartmentID);

------------------------------------------------------------------------------------------------------------------

You might also like