0% found this document useful (0 votes)
35 views46 pages

Comprehensive Guide to SQL Basics

The document provides a comprehensive overview of SQL (Structured Query Language) and MySQL, detailing the basics of SQL syntax, data types, operators, constraints, functions, data retrieval, joins, subqueries, views, indexes, transactions, and security. It also explains MySQL as an open-source relational database management system, its features, and various SQL commands for database management and manipulation. Additionally, it covers data definition, manipulation, and transaction control languages, along with constraints and their types.
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)
35 views46 pages

Comprehensive Guide to SQL Basics

The document provides a comprehensive overview of SQL (Structured Query Language) and MySQL, detailing the basics of SQL syntax, data types, operators, constraints, functions, data retrieval, joins, subqueries, views, indexes, transactions, and security. It also explains MySQL as an open-source relational database management system, its features, and various SQL commands for database management and manipulation. Additionally, it covers data definition, manipulation, and transaction control languages, along with constraints and their types.
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

SQL

(STRUCTURED QUERY LANUGAGE)


SQL ---------------- Structured Query Language.
1. Basics of SQL
- Introduction to SQL: SQL (Structured Query Language) is used to manage and manipulate
relational databases.
- SQL Syntax: Consists of keywords, clauses, and expressions.
- Data Types: Common types include INT, VARCHAR, DATE, etc.
- CREATE/DROP Database: CREATE DATABASE dbname; DROP DATABASE dbname;
- CREATE/DROP/ALTER Table: Used to define, delete, or change table structures.
- INSERT INTO: Adds new records to a table.
- SELECT: Retrieves data from tables.
- UPDATE: Modifies existing records.
- DELETE: Removes records.
- WHERE: Filters rows based on conditions.

2. Operators in SQL
- Arithmetic Operators: +, -, *, /
- Comparison Operators: =, =, <, >, <=, >=
- Logical Operators: AND, OR, NOT
- BETWEEN: Checks for range.
- IN: Matches values in a list.
- LIKE: Pattern matching.
- IS NULL: Checks for NULL values.
- Wildcards: % for multiple chars, _ for single char.

3. Constraints
- PRIMARY KEY: Uniquely identifies a row.
- FOREIGN KEY: Links to a primary key in another table.
- UNIQUE: Ensures all values in a column are different.
- NOT NULL: Disallows NULL values.
- DEFAULT: Provides default values for columns.
- CHECK: Ensures values meet a condition.
4. Functions
- Aggregate: COUNT (), SUM (), AVG (), MIN (), MAX ()
- String: CONCAT (), LENGTH (), SUBSTRING ()
- Date: NOW (), CURDATE (), DATE_ADD (), DATEDIFF ()
- Numeric: ROUND (), FLOOR (), CEIL ()

5. Data Retrieval & Filtering


- ORDER BY: Sort results.
- GROUP BY: Group rows for aggregation.
- HAVING: Filter after grouping.
- Aliases (AS): Rename columns/tables in output.
- DISTINCT: Returns unique results.

6. Joins
- INNER JOIN: Matches rows in both tables.
- LEFT JOIN: All rows from left + matched rows from right.
- RIGHT JOIN: All rows from right + matched rows from left.
- FULL JOIN: All rows from both tables.
- SELF JOIN: Table joined with itself.
- CROSS JOIN: Cartesian product of rows.

7. Subqueries
- Single-row: Returns one row.
- Multi-row: Returns multiple rows.
- Correlated: References outer query.
- EXISTS/NOT EXISTS: Checks for row existence.

8. Views
- CREATE VIEW: Virtual table from a query.
- UPDATE VIEW: Modify existing view.
- DROP VIEW: Remove a view.
- Advantages: Simplifies queries, improves security.
9. Indexes
- CREATE INDEX: Speeds up retrieval.
- Unique Index: No duplicates allowed.
- Composite Index: Multiple columns.
- DROP INDEX: Remove index.
- Clustered vs Non-Clustered: Clustered stores table rows in order; non-clustered stores
pointers.

10. Keys & Relationships


- Primary Key & Foreign Key.
- One-to-One, One-to-Many, Many-to-Many relationships.
- Referential Integrity: Ensures foreign key matches existing primary key.

11. Transactions
- BEGIN: Start a transaction.
- COMMIT: Save changes.
- ROLLBACK: Undo changes.
- ACID: Atomicity, Consistency, Isolation, Durability.
- SAVEPOINT: Rollback to a specific point.

12. Advanced SQL


- Stored Procedures: Precompiled SQL.
- User-Defined Functions: Custom functions.
- Triggers: Automatic actions on table events.
- Cursors: Row-by-row processing.
- Temporary Tables: Exist only during session.
- CTE: Named temporary result set.
- Window Functions: ROW_NUMBER (), RANK (), LEAD (), LAG ().

13. Performance & Optimization


- Optimize queries.
- Use indexes effectively.
- Analyse execution plans.
14. Security in SQL
- GRANT: Give access.
- REVOKE: Remove access.
- Roles: Group permissions.
- SQL Injection Prevention: Use parameterized queries.

15. Database Management


- Backup & Restore databases.
- Export & Import data.
- Partition tables.
- Replication for availability.
MYSQL
What is MySQL?
 MySQL is the most popular Open-Source Relational Database Management System.
 MySQL used for developing various web-based software development.
 Developed by Company MySQL AB.

Features Of MySQL:
 Relational Database Management System (RDBMS).
-- use of the retrieve the data.
 Easy to use.
 Storing data is secure.
 Open Source & Free to download.
 Compactable on many Operating System (Like, Windows, Mac OS, etc…)

Database & Tables:


 Multiple Individual tables joined in called RDBMS.

Example:
 Chained model (relating the one to another tables) is called Relational Database
Management System.
 Multiple tables relating using some keys.

Example:
 Foreign Key
 Primary Key

Queries:
 Create -------------------- New Database
 Drop---------------------- Drop Database
 Show--------------------- Show the databases
 Use----------------------- use the database
 Create table------------- Creating new table
 Show-------------------- Show the table
 Desc--------------------- Describe the table
 Alter--------------------- add new column
 Modify------------------ Modify the existing table
 Rename----------------- Rename the existing table_name
 Select --------------------- Retrieve the data
 Insert ---------------------- Insert some set of values
 Delete---------------------- Delete the table rows
 Update--------------------- Update the existing data
 Truncate------------------- Only table rows & columns removed
 Drop----------------------- Delete table
 Distinct-------------------- Hide Duplicate entries
 Group by------------------ Group of rows
 Order by------------------- Order by ASC,DESC
 Limit----------------------- Set of Limit rows
 AS(Alias Name) --------- Temporary Name
 Aggregate_Function----MAX, AVG, SUM, MIN, COUNT
 Wild card Queries------- %A, %A%, A%
 Not in --------------------- Avoid Particular
 IN-------------------------- only particular
 Between ------------------ Both value
 Like ----------------------- display the particular value
 Not Like ------------------ avoid particular value
 Join Queries-------------- Left Join, Right Join, Inner Join, Full Join(Union), Self Join

Data:
 It is a raw factor , Which describes the attributes of the entity.
 Execution of Information.

Database:
 It is a place or medium which we store the data format of Systematic and Organized.
 The Basic Operations: CRUD

1. CREATE / INSERT
2. READ / RETRIEVE
3. UPDATE / MODIFY
4. DELETE / DROP

DBMS:
 Expand – Database Management System
 It is a software which is used to maintain and arrange the database.
 Security and Authorization these are the two important features.
 We use Query Language to communicate to interact with DBMS.
 It is saved by Form of files.
RDBMS :
 Expand : Relational Database Management System.
 It is type of DBMS software , which we store the data.
 It is used to communicate SQL language.
 RDBMS stores the data stores in the form of database.
 It stores in the form of table.

Relational Model :
 It stores the data in the form of table.
 Any tables DBMS wants to become a RDBMS have to follow the relational model.
 It is a logical Organization of the data which consist of column and rows.
 Column and Rows developed by - EF CODD, in 1970.

Query language SQL

Data Database DBMS Relational RDBMS

Form of files tables in rows & column

Datatypes:
 It is used to specify or determine the type of data that will be stored in a particular
memory location.
 NUMBER -------- INT
 STRING ----------- “Name” Varchar “” (30), or we use single quotes ‘’
 BOOLEAN--------- True / False
 DECIMAL -------- Float / Double
 CHAR ------------ ‘a’
CONSTRAINTS
CONSTRAINTS:
It is a rule of given a column validation.

Types of constraints:

 NOT NULL ------------------------- Prevents missing values


 UNIQUE----------------------------- Avoids duplicates in a column
 PRIMARY KEY---------------------Uniquely identifies each record
 FOREIGN KEY--------------------- Maintains relationships between tables
 CHECK------------------------------ Applies custom validation rules
 DEFAULT--------------------------- Provides automatic default values
 AUTO_INCREMENT ------------ Automatically generates unique numeric IDs

NOT NULL:
 It ensures that cannot have null value.
 To make sure important fields like name, email.... etc...,

UNIQUE:

 It ensures all values in a column.


 To avoid duplicate entries.

PRIMARY KEY:

 It is a constraints which is used to identify a record uniquely from the table.


Characteristics of primary key:
 We have only one primary key in the table.
 Primary key value cannot be accept a duplicate values.
 Primary key cannot accept null.
 Primary key is always combination of unique and not null constraint.
FOREIGN KEY:

 It is used to establish a connection between the tables or create a relationship between


two tables.
 Characteristics of foreign key:
 We have only multiple foreign key in the table.
 Foreign key can accept duplication or repeated values.
 Foreign can accept null.
 Foreign key is a not combination of unique not null constraints.
 For an attribute(column) wants to become a foreign key. It is mandatory that it
must be a primary key in its is a own table.

CHECK:

 It is an extra validation with a condition. If the condition is satisfied then the values is
accepted. else if is rejected.

DEFAULT:

 Assign a default value if no value is given to autofill common values to reduce errors.

AUTO_INCREMENT:

 Automatically increased the numeric values for each row.

DATA DEFINITION LANGUAGE (DDL):

 In MySQL (and SQL in general), DDL stands for Data Definition Language.
 It is used to define, create, alter, and remove database objects such as tables,
schemas, indexes, and views.
1. CREATE-----------------------Creates a new database object (table, database, view, )
2. ALTER-------------------------Modifies the structure of an existing object .

(e.g.,add/remove columns).

3. DROP---------------------------Deletes an existing object permanently.


4. TRUNCATE-------------------Removes all rows from a table but keeps its structure.
5. RENAME----------------------Changes the name of an existing object.
DATA MANIPULATION LANGUAGE (DML):

 In MySQL (and SQL in general), DML stands for Data Manipulation Language.
 It is used to insert, update, delete, and retrieve data from database tables —
basically, it works on the records inside tables.
1. INSERT-----------------------------------------Adds new rows into a table.
2. UPDATE--------------------------------------- Modifies existing rows.
3. DELETE--------------------------------------- Removes rows from a table.
4. SELECT--------------------------------------- Retrieves data from one or more tables

TRANSACTION CONTROL LANGUAGE (TCL):

 In MySQL (and SQL in general), TCL stands for Transaction Control Language.
 It is used to manage transactions in a database to ensure data integrity and
consistency.
TCL commands work only with DML statements (INSERT, UPDATE, DELETE)
because those change the data.

COMMIT-------------Saves all changes made in the current transaction permanently

to the database.

ROLLBACK--------Reverts changes made in the current transaction

to the last committed state.

SAVEPOINT-------Sets a point within a transaction to which you can roll back later.

RELEASE SAVEPOINT--------------------Deletes a savepoint.

SET TRANSACTION-----------------------Sets the properties of a transaction

(like isolation level).


DDL:

ALTER TABLE:

 ALTER TABLE TABLE_NAME ADD COLUMN_NAME DATATYPE;

DROP COLUMN:

 ALTER TABLE TABLE_NAME DROP COLUMN_NAME;

MODIFY TABLE:

 ALTER TABLE TABLE_NAME MODIFY COLUMN COLUMN_NAME


DATATYPE;

ADD A CONSTRAINTS:

 ALTER TABLE TABLE_NAME MODIFY COLUMN_NAME DATATYPE


CONSTRAINTS;
 ALTER TABLE TABLE_NAME ADD CONSTRAINT CONSTRAINT_NAME OF
COLUMN_NAME;

DROP COMMANDS:

 DROP TABLE TBALE_NAME;

TRUNCATE COMMAND:

 TRUNCATE TABLE TABLE_NAME;

DML:

 SELECT---------------------TO RETREIVE THE DATA OR GET THE DATA


 *------------------------------TO I=DISPLAY THE DATA
 TABLE_NAME------------YOURS TABLE
INSERT METHOD:

Ther are two types, they are,

1. WITH ATTRIBUTES
2. WITHOUT ATTRIBUTES

(WITH ATTRIBUTES)

 INSERT INTO TBABLE_NAME (COLUMN1, COLUMN2,…)

VALUES (VALUE1, VALUE2 ..,);

(WITHOUT ATTRIBUTES)

 INSERT INTO TABLE_NAME VALUES(VALUE1, VALUE2 …..,)

SPECIFIC COLUMN IN THE TABLE:

 SELECT COLUMN_NAME1, COLUMN_NAME2 FROM TABLE_NAME;

DISTINCT:

 SELECT DISTINCT COLUMN_NAME1,COLUMN_NAME2 FROM


TABLE_NAME;

WHERE CONDITION:

 SELECT * FROM TABLE_NAME WHERE NAME=NAME;


 SELECT DISTINCT COLUMN_NAME1, COLUMN_NAME2 FROM
TABLE_NAME WHERE COLUMN_NAME=NAME;

(OR)

SELECT

DISTINCT

COLUMN_NAME1,

COLUMN_NAME2

FROM TABLE_NAME

WHERE COLUMN_NAME=NAME;
WHERE CONDITION:

 SELECT * FROM TABLE_NAME WHERE CONDITION;

SYNTAX TO ADD DATATYPE


1. ALTER TABLE TABLE_NAME ADD COLUMN_NAME VARCHAR(LENGTH);

2. ALTER TABLE TABLE_NAME ADD COLUMN_NAME INT;

3. ALTER TABLE TABLE_NAME ADD COLUMN_NAME DATE;

4. ALTER TABLE TABLE_NAME ADD COLUMN_NAME BOOLEAN;

5. ALTER TABLE TABLE_NAME ADD COLUMN_NAME DECIMAL

(FLOAT / DOUBLE);

SYNTAX TO ADD CONSTRAINTS


1. ALTER TABLE TABLE_NAME ADD CONSTRAINT CONSTRAINT_NAME
PRIMARY KEY (COLUMN_NAME);

2. ALTER TABLE TABLE_NAME ADD CONSTRAINT CONSTRAINT_NAME


FOREIGN KEY (COLUMN_NAME) REFERENCES (COLUMN_NAME);

3. ALTER TABLE TABLE_NAME ADD CONSTRAINT CONSTRAINT_NAME


UNIQUE (COLUMN_NAME);

4. ALTER TABLE TABLE_NAME ADD CONSTRAINT CONSTRAINT_NAME


CHECK (CONDITION);

5. ALTER TABLE TABLE_NAME ADD CONSTRAINT CONSTRAINT_NAME


PRIMARY KEY (COLUMN1, COLUMN2);
SYNTAX TO DROP CONSTRAINTS
1. ALTER TABLE TABLE_NAME DROP PRIMARY KEY;

2. ALTER TABLE TABLE_NAME DROP FOREIGN KEY CONSTRAINT_NAME;

3. ALTER TABLE TABLE_NAME DROP INDEX CONSTRAINT_NAME;

4. ALTER TABLE TABLE_NAME DROP CHECK CONSTRAINT_NAME;

5. ALTER TABLE TABLE_NAME DROP CONSTRAINT CONSTRAINT_NAME;

SYNTAX TO MODIFY DATATYPE|CONSTRAINTS


1. ALTER TABLE TABLE_NAME MODIFY COLUMN COLUMN_NAME
DATATYPE;

2. ALTER TABLE TABLE_NAME MODIFY COLUMN_NAME DATATYPE NOT


NULL;

3. ALTER TABLE TABLE_NAME ALTER COLUMN COLUMN_NAME SET


DEFAULT DEFAULT_VALUE;

SYNTAX TO DROP DATATYPE


 ALTER TABLE TABLE_NAME DROP COLUMN COLUMN_NAME;

DROP COMMAND
DROP TABLE TABLE_NAME;

 (IT WILL DELETE THE WHOLE TABLE)

TRUNCATE COMMAND
TRUNCATE TABLE_NAME; --------------(IT WILL DELETE THE COMPLETE
DATA FROM THE TABLE)
CONDITION:
TWO TYPES:
1. SIMPLE
2. COMPUND

SIMPLE--------- RELATIONAL OPERATORS


 (=,>=,<=,>,<,!=)

COMPOUND----------- LOGICAL OPERATORS


 (AND, OR, NOT)

1. AND-------BOTH CONDITION NEEDS BE TRUE


2. OR---------ANY ONE CONDITION BECOME A TRUE
3. NOT-------OPPOSITE REPLY

SYNTAX FOR WHERE CONDITION (RELATIONAL OPERATORS):

------SELECT * FROM TABLE_NAME WHERE NAME = VALUE;


------SELECT * FROM TABLE_NAME WHERE NAME >= VALUE;
------SELECT * FROM TABLE_NAME WHERE NAME <= VALUE;
------SELECT * FROM TABLE_NAME WHERE NAME ! = VALUE;
------SELECT * FROM TABLE_NAME WHERE NAME > VALUE;
------SELECT * FROM TABLE_NAME WHERE NAME < VALUE;

SYNTAX FOR WHERE CONDITION (LOGICAL OPERATORS):

-----SELECT*FROM TABLE_NAME WHERE CONDTION1 AND CONDTION2;

-----SELECT*FROM TABLE_NAME WHERE CONDTION1 OR CONDTION2;

-----SELECT*FROM TABLE_NAME WHERE NOT CONDTION1;


LIKE AND NOT LIKE SYNTAX:

-----SELECT * FROM EMPLOYEES WHERE NAME LIKE 'A%';

-----SELECT * FROM EMPLOYEES WHERE NAME LIKE "J%";

-----SELECT * FROM EMPLOYEES WHERE NAME LIKE "%E";

-----SELECT * FROM EMPLOYEES WHERE NAME LIKE "%I%";

-----SELECT * FROM EMPLOYEES WHERE NAME NOT LIKE "J%";

-----SELECT * FROM EMPLOYEES WHERE NAME NOT LIKE "%E";

-----SELECT * FROM EMPLOYEES WHERE NAME NOT LIKE "%I%";

-----SELECT * FROM EMPLOYEES WHERE ID LIKE 1;

-----SELECT * FROM EMPLOYEES WHERE SALARY LIKE "5%";

-----SELECT * FROM EMPLOYEES WHERE HIRE_DATE LIKE "%15";

BETWEEN SYNTAX:

SELECT * FROM EMPLOYEES

WHERE HIRE_DATE BETWEEN "2021-01-10" AND "2022-03-15";

ORDER BY SYNTAX:

------SELECT * FROM TBALE_NAME ORDER BY SALARY ASC;

------SELECT * FROM TABLE_NAME ORDER BY SALARY DESC;

IN SYNAX:

SELECT * FROM TABLE_NAME

WHERE COLUMN_NAME IN(VALUE1,VALUE2,VALUE3);


NOT IN SYNTAX:

SELECT * FROM TABLE_NAME

WHERE COLUMN_NAME NOT IN(VALUE1,VALUE2);

LIMIT SYNTAX:

SELECT * FROM TABLE_NAME LIMIT 3;

UPDATE :

 Is Used to modify the existing the data.

SYNTAX:

UPDATE TABLE_NAME SET COLUMN_NAME = VALUE

WHERE COLUMN_NAME = VALUE;

DELETE :

 Is used to delete the specific rows from the table.

SYNTAX:

DELETE FROM TABLE_NAME WHERE COLUMN_NAME=VALUES;

COMMIT:

 Permanent save the data.

ROLLBACK:

 Undo the statement of commit.


 Temporary data cannot show and show the permanent data only.
AGGREGATE FUNCTIONS

 To evaluate the different of values of the column.

( SUM, AVG, MIN, MAX, COUNT )

COUNT()----------------Counts the number of rows (or non-NULL values in a column).

SUM() -------------------Adds up all numeric values in a column.

AVG()--------------------Calculates the average value of a numeric column.

MIN()--------------------Returns the smallest value in a column.

MAX()-------------------Returns the largest value in a column.

SYNATX FOR AGGREGATE_FUNCTIONS:

-------SELECT SUM(COLUMN_NAME) FROM TABLE_NAME;

-------SELECT COUNT(COLUMN_NAME) FROM TABLE_NAME;

(OR)

-------SELECT COUNT(*) FROM TABLE_NAME;

-------SELECT MIN(COLUMN_NAME) FROM TABLE_NAME;

-------SELECT MAX(COULMN_NAME) FROM TABLE_NAME;

-------SELECT AVG(COLUMN_NAME) FROM TABLE_NAME;

COUNT (SYNTAX):

SELECT COUNT(DISTINCT TABLE_NAME) FROM TABLE_NAME;


GROUP BY

 It is used to group the rows that have the same values in one or more column.

SYNTAX:

SELECT COLUMN1,AGGREGATE_FUNCTION(COLUMN2)

FROM TABLE_NAME GROUP BY COLUMN1;

AS----ALIAS NAME:

 It is giving a Temporary name is called alias name (AS).

SYNTAX:

SELECT COLUMN1,AGGREGATE_FUNCTION(COLUMN2) AS TOTAL_SALES


FROM SALES GROUP BY EMPLOYEE;

EXAMPLE:

SELECT EMPLOYEE ,SUM(AMOUNT) AS TOTAL_SALES FROM SALES


GROUP BY EMPLOYEE;

HAVING CLAUSE:

 The HAVING clause in SQL is used to filter the results after an aggregation is
performed — kind of like a WHERE clause, but for grouped data.
 It is perform specific calculation in order by (asc, desc) condition in having clause.

SYNTAX:

SELECT COLUMN1,AGGREGATE_FUNCTION(COLUMN2) AS TOTAL FROM


TABLE_NAME GROUP BY COLUMN1 HAVING TOTAL>VALUE ORDER BY ASC;

(OR)

HAVING AGGREGATE_FUNCTION(COLUMN2)> VALUE;


JOIN QUERIES

 Join helps to retrieve the data from two or more databases tables.
 The tables are mutually related to using primary key and foreign key.

TYPES OF JOIN QUERIES:

INNER JOIN

 Returns only the rows where there is a match in both tables.

LEFT JOIN

 Returns all rows from the left table, and matching rows from the right table.
 If there’s no match, NULL is shown for right table columns.

RIGHT JOIN

 Returns all rows from the right table, and matching rows from the left table.

FULL JOIN (UNION)

 Returns all rows from both tables, with NULL where there’s no match.

NOTE:

 MySQL doesn’t directly support FULL JOIN, but you can simulate it with UNION

SELF JOIN

 You treat the same table as two different tables by giving it aliases.

 You match rows based on a relationship between columns in the same table.
TABLE JOIN SYNTAX:

SELECT * FROM TABLES_NAME1 INNER JOIN TABLE_NAME2;

INNER JOIN:

SELECT * FROM TABLES_NAME1 INNER JOIN TABLE_NAME2 ON


TABLE_NAME1.COLUMN_NAME=TABLE_NAME2.COLUM_NAME;

LEFT JOIN:

SELECT * FROM TABLES_NAME1 LEFT JOIN TABLE_NAME2 ON


TABLE_NAME1.COLUMN_NAME=TABLE_NAME2.COLUM_NAME;

RIGHT JOIN:

SELECT * FROM TABLES_NAME1 RIGHT JOIN TABLE_NAME2 ON


TABLE_NAME1.COLUMN_NAME=TABLE_NAME2.COLUM_NAME;

FULL JOIN (UNION):

SELECT * FROM TABLES_NAME1 LEFT JOIN TABLE_NAME2 ON


TABLE_NAME1.COLUMN_NAME=TABLE_NAME2.COLUM_NAME;

UNION

SELECT * FROM TABLES_NAME1 RIGHT JOIN TABLE_NAME2 ON


TABLE_NAME1.COLUMN_NAME=TABLE_NAME2.COLUM_NAME;
SELF JOIN:

SYNTAX 1:

SELECT * FROM TABLE_NAME AS_NAME_1

LEFT JOIN

TABLE_NAME

AS_NAME_2 ON

AS_NAME_1.COLUMN_NAME_1 = AS_NAME_2.COLUMN_NAME_2;

EXAMPLE:

SELECT * FROM EMPLOYEES X LEFT JOIN EMPLOYEES Y

ON

X.EMP_NAME = Y.MANAGER_ID;

SYNTAX 2

SELECT AS_NAME_1.COLUMN_NAME_1 , AS_NAME_2.COLUMN_NAME_2

FROM

TABLE_NAME AS_NAME_1

LEFT JOIN

TABLE_NAME AS_NAME_2

ON AS_NAME_1.COLUMN_NAME_1 = AS_NAME_2.COLUMN_NAME_2;

EXAMPLE:

SELECT E.EMP_NAME, F.MANAGER_ID FROM EMPLOYEES E

LEFT JOIN

EMPLOYEES F ON

E.EMP_NAME = F.MANAGER_ID;
SUB QUERIES

 A subquery (also called an inner query or nested query) is a query inside another
SQL query.
 It’s used when you need the result of one query to help run another query.

There are two types, they are,

1. INNER QUERY
2. OUTER QUERY

Think of it is like this :

 Inner query → helper, gets the needed data first.


 Outer query → final decision-maker, uses that data to produce the final result.

INNER QUERY:

 An inner query is just another name for a subquery — specifically, it’s the query that is
nested inside the main (outer) query.
 The outer query uses the result of the inner query to complete its execution.

SYNTAX:

SELECT AGGREGATE_FUNCTION(COLUMN) FROM TABLE_NAME;

OUTER QUERY:

 An outer query is the main query that wraps around an inner query (subquery).
It’s the query that receives and uses the result returned by the inner query.

SYNTAX:

--------SELECT * FROM TABLE_NAME WHERE COLUMN >( SELECT


AGGREGATE_FUNCTION(COLUMN) FROM TABLE_NAME);

--------SELECT * FROM TABLE_NAME WHERE COLUMN > ( INNER QUERY );


INNER QUERY --------- SELECT AGGREGATE_FUNCTION(COLUMN) FROM
TABLE_NAME;

EXAMPLE:

INNER QUERY & OUTER QUERY

---SELECT * FROM PRODUCTS WHERE PRODUCT_NAME= "RULER"; /* INNER */

---SELECT * FROM PRODUCTS WHERE PRICE < (SELECT PRICE FROM PRODUCTS
WHERE PRODUCT_NAME= "RULER"); /* OUTER */

(OR)

---SELECT * FROM PRODUCTS WHERE PRICE < (INNER QUERY);

IDENTIFY 2ND & 3RD MIN & MAX VALUE

EXAMPLE OF SUB_QUERIES OF MAX (APART QUERY):

MAX:

------SELECT MAX(PRICE) FROM PRODUCTS WHERE PRICE <

(SELECT MAX(PRICE) FROM PRODUCTS WHERE PRICE <

(SELECT MAX(PRICE) FROM PRODUCTS));

MIN:

EXAMPLE OF SUB_QUERIES OF MIN(APART QUERY) :

------SELECT MIN(PRICE) FROM PRODUCTS WHERE PRICE>

(SELECT MIN(PRICE) FROM PRODUCTS WHERE PRICE>

(SELECT MIN(PRICE) FROM PRODUCTS));


COMPARISON OPERATOR
ALL:
 All Values in the sub query must be true for everyone

SYNTAX:
-------SELECT * FROM TABLE_NAME WHERE COLUMN_NAME =”VALUE”
-------SELECT * FROM TABLE_NAME WHERE COUMN_NAME >ALL
( INNER QUERY)

EXAMPLE:
---SELECT * FROM EMPLOYEES WHERE DEPARTMENT ="HR"; /* #50000,48000 */
---SELECT * FROM EMPLOYEES WHERE SALARY > ALL(SELECT SALARY FROM
EMPLOYEES WHERE DEPARTMENT ="HR");

ANY
 It is used to comparison operator to compare a value two any value return by a sub
query.

SYNTAX:
-------SELECT * FROM TABLE_NAME WHERE COLUMN_NAME =”VALUE”
-------SELECT * FROM TABLE_NAME WHERE COUMN_NAME >ANY
( INNER QUERY)

EXAMPLE:
------SELECT * FROM EMPLOYEES WHERE DEPARTMENT ="SALES";
------SELECT * FROM EMPLOYEES WHERE SALARY < ANY(SELECT SALARY
FROM EMPLOYEES WHERE DEPARTMENT ="SALES");
EXISTS OR NOT EXISTS:
EXISTS
 In the sub query returns atleast one row.

SYNTAX:
-------SELECT * FROM TABLE_NAME WHERE COLUMN_NAME =”VALUE”
-------SELECT * FROM TABLE_NAME WHERE EXISTS( INNER QUERY)

EXAMPLE:
-------SELECT * FROM EMPLOYEES WHERE SALARY ="70000";
-------SELECT * FROM EMPLOYEES WHERE EXISTS(SELECT NAME FROM
EMPLOYEES WHERE SALARY >"70000");

NOT EXISTS:
 In the sub query is not return.

SYNTAX:
-------SELECT * FROM TABLE_NAME WHERE COLUMN_NAME =”VALUE”
-------SELECT * FROM TABLE_NAME WHERE NOT EXISTS ( INNER QUERY)

EXAMPLE:
-------SELECT * FROM EMPLOYEES WHERE SALARY ="30000";
-------SELECT * FROM EMPLOYEES WHERE NOT EXISTS(SELECT NAME FROM
EMPLOYEES WHERE SALARY <30000);
WINDOWS FUNCTIONS
 The windows function performs a calculation across a set of table rows. some how
related to the current row.
 It's a regular SQL function like AVG, SUM and etc.., But instead grouping rows
together like group by it allows you to see the result per row.

Difference between regular function and windows function:

REGULAR FUNCTION:
 regular function with group by combines rows into one result per group. we use the
individual rows.

WINDOWS FUNCTION:
 Keep all rows but add extra info like total, ranking based on related rows.

FUNCTIONS:
ROW NUMBER
 It Gives a unique number to each row. Starting form 1 , no matter if the values repeat.

RANK
 It gives a ranking number if two rows are tie, they get same rank and skip the next
number.

DENSE RANK
 It's like a rank only, but doesn't skip the numbers after tie.

SUM
 To Calculate a running total.

AVG
 To calculate a running average
LAG
 It shows the values from the previous row.

LEAD
 It shows the next sales values for each row.

PARTITION BY
 To divide the results set into partition group. (Literally Group By Condition)
 The way of apply a function a group of rows but without collapsing then like group by
does.

OVER
 Apply a function across a function without collapsing a result.

IN
 The IN operator is used to test if a value exists within a set of given values or results
from a subquery.
 It is essentially a shorthand for multiple OR conditions.
KEYWORD: IN

EXAMPLE:
----------SELECT * FROM EMPLOYEES WHERE DEPARTMENT IN
(SELECT DEPARTMENT FROM EMPLOYEES WHERE NAME ="BOB");

NOT IN:
 The NOT IN operator checks if a value does NOT exist in a list or subquery results.
 It is a shorthand for multiple AND conditions with inequality.
KEYWORD: NOT IN

EXAMPLE:
---------SELECT * FROM EMPLOYEES WHERE DEPARTMENT NOT IN
(SELECT DEPARTMENT FROM EMPLOYEES WHERE NAME ="EVA");
SYNTAX FOR OVER AND PARTITION BY:
----SELECT EMPLOYEE_NAME,SALE_DATE,SALE_AMOUNT
OVER(PARTITION BY EMPLOYEE_NAME ORDER BY SALE_DATE)
AS RUNNING TOTAL
FROM SALES;

SYNTAX FOR RANK:


---------SELECT NAME, DEPARTMENT, SALARY, RANK()OVER
(PARTITION BY DEPARTMENT ORDER BY SALARY ASC) AS RANK_SALARY
FROM EMPLOYEES;

SYNTAX FOR DENSE RANK:


---------SELECT NAME, DEPARTMENT, SALARY, DENSE_RANK()OVER
(PARTITION BY DEPARTMENT ORDER BY SALARY ASC) AS RANK_SALARY
FROM EMPLOYEES;

SYNTAX FOR LAG:


---------SELECT NAME, DEPARTMENT, SALARY, LAG
(SALARY)OVER(PARTITION BY DEPARTMENT ORDER BY SALARY ASC)
AS LAG_NO
FROM EMPLOYEES;

SYNTAX FOR LEAD:


SELECT NAME, DEPARTMENT, SALARY, LEAD
(SALARY)OVER(PARTITION BY DEPARTMENT ORDER BY SALARY DESC)
AS LAG_NO
FROM EMPLOYEES;
FIRST VALUE:
 In Windows function that return the first value in a group called a partition based on
the order you defined.
 Only see the rows from the first row to the current row.
 Returns the first value in an ordered partition of a result set.
Ex:
 if you short the salary in DESC order in each dept ,first value(salary) will given
highest value

SYNTAX:
FOR ORDER BY DESC:
-----------SELECT NAME, DEPARTMENT, SALARY, FIRST_VALUE
(SALARY)OVER(PARTITION BY DEPARTMENT ORDER BY SALARY DESC)
AS FV_VALUE
FROM EMPLOYEES;

FOR ORDER BY ASC:


-----------SELECT NAME, DEPARTMENT, SALARY, FIRST_VALUE
(SALARY)OVER(PARTITION BY DEPARTMENT ORDER BY SALARY ASC)
AS FV_VALUE
FROM EMPLOYEES;

LAST VALUE:
 last value it returns in the specified column in the current window based on order by
condition.
 Returns the last value in an ordered partition of a result set.
 Only see the rows from the last row to the current row.

SYNTAX :
FOR ORDER BY DESC:
---------SELECT NAME, DEPARTMENT, SALARY, LAST_VALUE
(SALARY)OVER(PARTITION BY DEPARTMENT ORDER BY SALARY DESC)
AS FV_VALUE FROM EMPLOYEES;
FOR ORDER BY ASC:
-----------SELECT NAME, DEPARTMENT, SALARY, LAST_VALUE
(SALARY)OVER(PARTITION BY DEPARTMENT ORDER BY SALARY ASC)
AS FV_VALUE
FROM EMPLOYEES;

ROW BETWEEN:
 Its starts from group of rows look at which row to which row should i look.

UNBOUNDED PRESIDING--------NO LIMIT


 It's starts from the first row in the group.
Unbound-No limit
Presiding-between its is included current and future rows.

UNBOUND FOLLOWING:
 Go let the very last row into the group following is equal to rows after the current one.

SYNTAX: (UNBOUNDED FOLLOWING & UNBOUNDED PRESIDING)


FOR ORDER BY DESC:
-------------SELECT NAME, DEPARTMENT, SALARY, LAST_VALUE
(SALARY)OVER(PARTITION BY DEPARTMENT ORDER BY SALARY DESC
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING )
AS LASTSVALUE
FROM EMPLOYEES;

FOR ORDER BY ASC:


-------------SELECT NAME, DEPARTMENT, SALARY, LAST_VALUE
(SALARY)OVER(PARTITION BY DEPARTMENT ORDER BY SALARY ASC
ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING )
AS LASTSVALUE FROM EMPLOYEES;
STORE PROCEDURES
 In MySQL, a Stored Procedure is a set of SQL statements that you save in the
database so you can run them later by calling their name, instead of rewriting the SQL
each time.
 It’s like creating a function in programming but for SQL operations.
 Its a pre-defined block of code that is saved and its stored it in the database. can be
executed later with the single comment.

1. Why use Stored Procedures?


 Reusability – Write once, use many times.
 Maintainability – Easy to update in one place.
 Security – Hide complex SQL logic from end users.
 Performance – Stored in compiled form inside the database.

SYNTAX - 1:

CREATE PROCEDURE `new_procedure` ()


BEGIN
// -------- SQL Statements
END

SYNATX – 2:

DELIMITER //
CREATE PROCEDURE procedure_name ([IN | OUT | INOUT] param_name datatype, ...)
BEGIN
// -- SQL statements
END //
DELIMITER ;
EXAMPLE: (SYNTAX 1):
USE BYE;
CALL SALES_INFO;
DESC SALES;
SELECT EMPLOYEE_NAME FROM SALES WHERE SALE_AMOUNT ="ALICE";

EXAMPLE (SYNTAX 2):

FOR IN:
CREATE DEFINER=`root`@`localhost` PROCEDURE `get_briyani_info`(in salary int)
BEGIN
FROM EMPLOYEES WHERE [Link] = SALARY;
END

FOR OUT:
CREATE DEFINER=`root`@`localhost` PROCEDURE `SET_LORRY_INFO`(IN SALARY
INT)
BEGIN
------SELECT * FROM EMPLOYEES;
------SELECT * FROM EMPLOYEES WHERE NAME = "ALICE";
------SELECT NAME, SALARY FROM EMPLOYEES WHERE
[Link]=SALARY;
END

FOR INOUT:
CREATE DEFINER=`ROOT`@`LOCALHOST`
PROCEDURE `GET_BEER_INFO`(INOUT ITALY INT, IN SALARY INT)
BEGIN

--------------SELECT COUNT (*) INTO ITALY FROM EMPLOYEES WHERE


[Link] = SALARY;
END
TRIGGERS
 In MySQL, a Trigger is a special stored program that automatically runs (fires) in
response to a specific event on a table, such as an INSERT, UPDATE, or DELETE.
 It’s like setting an automatic reaction to changes in the database.
 There are three conditions only, they are

o INSERT
o UPDATE
o DELETE

1. Why use Triggers?


 Data validation before saving.
 Audit logging (track changes to a table).
 Maintain related tables automatically.
 Enforce business rules at the database level.

SYNTAX:

CREATE TRIGGER trigger_name


{BEFORE | AFTER} {INSERT | UPDATE | DELETE}
ON table_name
FOR EACH ROW
BEGIN
-- SQL statements to execute
END;
Types of Triggers in MySQL

Timing Event

BEFORE INSERT

BEFORE UPDATE

BEFORE DELETE

AFTER INSERT

AFTER UPDATE

AFTER DELETE

Part Meaning

`CREATE TRIGGER` Starts the trigger definition


`trigger_name` A unique name for your trigger
`BEFORE` / `AFTER` When the trigger runs (before/after the event)
`INSERT` / `UPDATE` / `DELETE` What event triggers it
`ON table_name` The table the trigger is linked to
`FOR EACH ROW` Runs the trigger **once per row affected**
`BEGIN ... END` Block of SQL code to execute
INSERT METHOD:
In MySQL triggers,
 BEFORE INSERT → runs before a new row is inserted into the table.
 AFTER INSERT → runs after the new row is inserted into the table.

BEFORE INSERT:
 BEFORE INSERT in MySQL is a trigger type that runs before a new row is actually
inserted into a table.
 It lets you check, validate, or modify the incoming data before MySQL saves it.
 Step 1 --------------- before insert trigger (create table table_name)
 Step 2---------------- create trigger syntax

SYNTAX:
DELIMITER //
CREATE TRIGGER trigger_name
BEFORE INSERT ON table_name
FOR EACH ROW
BEGIN
-- SQL Statements
END //

DELIMITER ;

EXAMPLE:
DELIMITER //
CREATE TRIGGER AGE_IDENTIFY
BEFORE INSERT
ON CUSTOMERS
FOR EACH ROW
IF [Link]<18 THEN
SET [Link]=18;
END IF; //
AFTER INSERT :
 AFTER INSERT in MySQL is a trigger type that runs after a new row is
successfully inserted into a table.
 It’s useful when you want to perform actions based on the new data but don’t need
to (or can’t) change it anymore.

SYNTAX:
DELIMITER //
CREATE TRIGGER trigger_name
AFTER INSERT ON table_name
FOR EACH ROW
BEGIN
-- actions after insertion
END //

DELIMITER ;

EXAMPLE CODE OF INSERT METHOD:


CREATE DATABASE TRIGERS;
USE TRIGERS;
# STEP 1 : BEFORE INSERT TRIGGER
CREATE TABLE CUSTOMERS(CUST_ID INT,NAME VARCHAR(30),AGE INT);
# STEP 2 : CREATE TRIGGER
DELIMITER //

CREATE TRIGGER AGE_VERIFY


BEFORE INSERT
ON CUSTOMERS
FOR EACH ROW
IF [Link]<18 THEN SET [Link] = 0;

END IF; //
INSERT INTO CUSTOMERS VALUES(10,"VIRAT",20),
(20,"VK",10),
(30,"KL",-10),
(40,"RB",40),
(50,"MSD",13);

SELECT*FROM CUSTOMERS;

# AFTER INSERT TRIGGER EVENT

CREATE TABLE CUSTOMERS1(


ID INT AUTO_INCREMENT PRIMARY KEY,
NAME VARCHAR(40) NOT NULL,
EMAIL VARCHAR(30),
BIRTHDATE DATE);

# CREATE MESSAGE TABLE


CREATE TABLE MESSAGE(
ID INT AUTO_INCREMENT,
MESSAGEID INT ,
MESSAGE VARCHAR(300) NOT NULL,
PRIMARY KEY(ID,MESSAGEID)
);
# CRAETE TRIGGER AFTER INSERT
DELIMITER //
CREATE TRIGGER CHECK_NULL_DOB
AFTER INSERT
ON CUSTOMERS2
FOR EACH ROW
IF [Link] IS NULL THEN
INSERT INTO MESSAGE(MESSAGEID,MESSAGE)
VALUES
([Link] , CONCAT('HI', [Link], 'PLEASE UPDATE YOUR DATE OF BIRTH'));
END IF ;
END //
DELIMITER ;

# INSERT INTO MESSAGE TABLE VALUES

INSERT INTO CUSTOMERS2(NAME, EMAIL, BIRTHDATE)


VALUES
("VK","VK@[Link]", NULL),
("TK","TK@[Link]","1999-07-2");

INSERT INTO CUSTOMERS2(NAME, EMAIL, BIRTHDATE)


VALUES
(" RAHUL ","RAHUL@[Link]",NULL);

#CALL ERROR TABLE


SELECT * FROM MESSAGE;
#CALL EXECUTION TABLE
SELECT * FOM CUSTOMERS;
UPDATE METHOD:
In MySQL, you can have two types of triggers for updates:
1. BEFORE UPDATE → runs before the row is updated
2. AFTER UPDATE → runs after the row is updated

BEFORE INSERT:
 BEFORE UPDATE in MySQL is a trigger type that runs before MySQL updates a
row in the table.
 It lets you check, modify, or block the new values before they are saved.

SYNTAX:
DELIMITER //

CREATE TRIGGER trigger_name


BEFORE UPDATE ON table_name
FOR EACH ROW
BEGIN
-- SQL Statements
END //

EXAMPLE:
DELIMITER //

CREATE TRIGGER EMP_TRIGGR


BEFORE UPDATE
ON EMPLOYEES
FOR EACH ROW
BEGIN IF [Link] = 10000 THEN
SET [Link]=85000;
ELSEIF [Link]<10000 THEN
SET [Link] =72000;
END IF;
END //
AFTER UPDATE:
 AFTER UPDATE in MySQL is a trigger type that runs after a row has been
successfully updated in a table.
 Unlike BEFORE UPDATE, you cannot modify the new data here — the update is
already done. Instead, you use it to log changes, update related tables, or send
notifications.

SYNTAX:
DELIMITER //

CREATE TRIGGER trigger_name


AFTER UPDATE ON table_name
FOR EACH ROW
BEGIN
-- SQL Statements
END //

DELIMITER ;

EXAMPLE OF UPDATE METHOD:

CREATE DATABASE TRIO;


USE TRIO;

CREATE TABLE EMPLOYEES(


ID INT PRIMARY KEY,
NAME VARCHAR(30),
AGE INT,
SALARY FLOAT);
INSERT INTO EMPLOYEES VALUES
(10,"SARALA",18,50000),
(20,"SABARI",19,40000),
(30,"SHAKASH",10,30000),
(40,"SATHISH",16,20000),
(50,"POOJA",20,10000);

DELIMITER //
CREATE TRIGGER DEVIL_GRILL
BEFORE UPDATE
ON EMPLOYEES
FOR EACH ROW
BEGIN
IF [Link] = 10000 THEN
SET [Link] = 85000;
ELSEIF [Link] < 10000 THEN
SET [Link] = 72000;
END IF;
END//

UPDATE EMPLOYEES
SET SALARY = 10000;

UPDATE EMPLOYEES
SET SALARY = 5000;

UPDATE EMPLOYEES
SET SALARY = 5000;
SELECT*FROM EMPLOYEES;
DELETE METHOD:
 In MySQL, a DELETE trigger automatically runs when a row is deleted from a
table.
There are two types:
1. BEFORE DELETE → runs before the row is removed.
2. AFTER DELETE → runs after the row is removed.

BEFORE DELETE:
 BEFORE DELETE in MySQL is a trigger type that runs before a row is deleted
from a table.
 It’s mainly used for validation, preventing deletion, or taking backup of data
before removal.

SYNTAX:
DELIMITER //
CREATE TRIGGER trigger_name
BEFORE DELETE ON table_name
FOR EACH ROW
BEGIN
-- actions before deleting
END //

EXAMPLE:
DELIMITER $$
CREATE TRIGGER SALARY_DELETE
BEFORE DELETE
ON SALARY
FOR EACH ROW
BEGIN
INSERT INTO SALARYDEL(EID,VALIDFROM,AMOUNT)
VALUE([Link],[Link],[Link]);
END $$
DELIMITER ;
AFTER DELETE:
 AFTER DELETE in MySQL is a trigger type that runs after a row has been deleted
from a table.
 It’s mainly used for logging, cleaning up related data, or updating summary
tables.
Unlike BEFORE DELETE, you cannot prevent the deletion here because the row is
already gone.

SYNTAX:
DELIMITER //

CREATE TRIGGER trigger_name


AFTER DELETE ON table_name
FOR EACH ROW
BEGIN
-- SQL Statements
END //

EXAMPLE OF CODE DELETE METHOD


CREATE DATABASE TOM;
USE TOM;

CREATE TABLE SALARY(


EID INT PRIMARY KEY,
VALIDFROM DATE NOT NULL,
AMOUNT FLOAT NOT NULL);

INSERT INTO SALARY (EID,VALIDFROM,AMOUNT)


VALUES(100,'2005-05-01',55000),
(101,'2007-08-01',65000),
(102,'2006-09-01',75000),
(103,'2009-04-01',85000);
SELECT*FROM SALARY;

CREATE TABLE SALARYDEL(


ID INT PRIMARY KEY AUTO_INCREMENT,
EID INT ,
VALIDFROM DATE NOT NULL,
AMOUNT FLOAT NOT NULL,
DELETEDAT TIMESTAMP DEFAULT NOW());

DELIMITER $$
CREATE TRIGGER SALARY_DELETE
BEFORE DELETE
ON SALARY
FOR EACH ROW
BEGIN

INSERT INTO SALARYDEL(EID,VALIDFROM,AMOUNT)


VALUE([Link],[Link],[Link]);

END $$
DELIMITER ;

DELETE FROM SALARY


WHERE EID = 101;

SELECT*FROM SALARYDEL;

You might also like