Comprehensive Guide to SQL Basics
Comprehensive Guide to SQL Basics
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 ()
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.
11. Transactions
- BEGIN: Start a transaction.
- COMMIT: Save changes.
- ROLLBACK: Undo changes.
- ACID: Atomicity, Consistency, Isolation, Durability.
- SAVEPOINT: Rollback to a specific point.
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…)
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.
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:
It ensures that cannot have null value.
To make sure important fields like name, email.... etc...,
UNIQUE:
PRIMARY KEY:
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:
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).
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
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.
to the database.
SAVEPOINT-------Sets a point within a transaction to which you can roll back later.
ALTER TABLE:
DROP COLUMN:
MODIFY TABLE:
ADD A CONSTRAINTS:
DROP COMMANDS:
TRUNCATE COMMAND:
DML:
1. WITH ATTRIBUTES
2. WITHOUT ATTRIBUTES
(WITH ATTRIBUTES)
(WITHOUT ATTRIBUTES)
DISTINCT:
WHERE CONDITION:
(OR)
SELECT
DISTINCT
COLUMN_NAME1,
COLUMN_NAME2
FROM TABLE_NAME
WHERE COLUMN_NAME=NAME;
WHERE CONDITION:
(FLOAT / DOUBLE);
DROP COMMAND
DROP TABLE TABLE_NAME;
TRUNCATE COMMAND
TRUNCATE TABLE_NAME; --------------(IT WILL DELETE THE COMPLETE
DATA FROM THE TABLE)
CONDITION:
TWO TYPES:
1. SIMPLE
2. COMPUND
BETWEEN SYNTAX:
ORDER BY SYNTAX:
IN SYNAX:
LIMIT SYNTAX:
UPDATE :
SYNTAX:
DELETE :
SYNTAX:
COMMIT:
ROLLBACK:
(OR)
COUNT (SYNTAX):
It is used to group the rows that have the same values in one or more column.
SYNTAX:
SELECT COLUMN1,AGGREGATE_FUNCTION(COLUMN2)
AS----ALIAS NAME:
SYNTAX:
EXAMPLE:
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:
(OR)
Join helps to retrieve the data from two or more databases tables.
The tables are mutually related to using primary key and foreign key.
INNER JOIN
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.
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:
INNER JOIN:
LEFT JOIN:
RIGHT JOIN:
UNION
SYNTAX 1:
LEFT JOIN
TABLE_NAME
AS_NAME_2 ON
AS_NAME_1.COLUMN_NAME_1 = AS_NAME_2.COLUMN_NAME_2;
EXAMPLE:
ON
X.EMP_NAME = Y.MANAGER_ID;
SYNTAX 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:
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.
1. INNER QUERY
2. OUTER QUERY
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:
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:
EXAMPLE:
---SELECT * FROM PRODUCTS WHERE PRICE < (SELECT PRICE FROM PRODUCTS
WHERE PRODUCT_NAME= "RULER"); /* OUTER */
(OR)
MAX:
MIN:
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.
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 ORDER BY DESC:
-----------SELECT NAME, DEPARTMENT, SALARY, FIRST_VALUE
(SALARY)OVER(PARTITION BY DEPARTMENT ORDER BY SALARY DESC)
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.
UNBOUND FOLLOWING:
Go let the very last row into the group following is equal to rows after the current one.
SYNTAX - 1:
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";
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
o INSERT
o UPDATE
o DELETE
SYNTAX:
Timing Event
BEFORE INSERT
BEFORE UPDATE
BEFORE DELETE
AFTER INSERT
AFTER UPDATE
AFTER DELETE
Part Meaning
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 ;
END IF; //
INSERT INTO CUSTOMERS VALUES(10,"VIRAT",20),
(20,"VK",10),
(30,"KL",-10),
(40,"RB",40),
(50,"MSD",13);
SELECT*FROM CUSTOMERS;
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 //
EXAMPLE:
DELIMITER //
SYNTAX:
DELIMITER //
DELIMITER ;
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 //
DELIMITER $$
CREATE TRIGGER SALARY_DELETE
BEFORE DELETE
ON SALARY
FOR EACH ROW
BEGIN
END $$
DELIMITER ;
SELECT*FROM SALARYDEL;