SQL Joins and Data Manipulation Guide
SQL Joins and Data Manipulation Guide
UPDATE TABLE
SET columnName = null
WHERE YourCondition // A specific Column Value delete
-: DATABASE:-
Joins:-
A SQL Join statement is used to combine data or rows from two or more tables based on a
common field between them.
We can join two tables without primary key , The column just have to have same data
type there are a few ways to combine two tables without a common column, including
CROSS JOIN (Cartesian product) and UNION. The latter is technically not a join but can
be handy for merging tables in SQL.
Join can also be made by taking such a column that is primary key in both tables.
ImpNote:- Both Self Join and Equi Join are types of INNER Join in
SQL
Example1:-
SELECT [Link], [Link]
FROM Orders
INNER JOIN Customers ON [Link] = [Link];
(Note: The INNER JOIN keyword selects all rows from both tables as long as
there is a match between the columns. If there are records in the "Orders" table
that do not have matches in "Customers", these orders will not be shown!)
Example2:
JOIN T2 b ON [Link]=[Link]
2)Left Join:-
Left Join returns all the rows of Left Table and the match row of Right Table.
The following SQL statement will select all customers, and any orders they
might have: mtlb agr kisi customer na order naib hi kiya wa tb bhi uska
name display hooga aur [Link] ki jagah null display hoo jaye ga
Example
SELECT [Link], [Link]
FROM Customers
LEFT JOIN Orders ON [Link] = [Link]
ORDER BY [Link];
Example
SELECT [Link], [Link], [Link]
FROM Orders
RIGHT JOIN Employees ON [Link] = [Link]
ORDER BY [Link];
Exp:-
(Agr hm daikhna chahty wou cutomers jinhou na order place kiye) + (wou
jinhou na order place ni kiye) + (wou orders jinky customers is table ma nai
ha)
Example
SELECT [Link], [Link]
FROM Customers
FULL OUTER JOIN Orders ON [Link]=[Link]
ORDER BY [Link];
Note: FULL OUTER JOIN can potentially return very large result-sets!
Tip: FULL OUTER JOIN and FULL JOIN are the same.
5)Self Join:-
You use a self join when a table references data in itself.
E.g., an Employee table may have a managerID column that points to the employee that is the
manager of the current employee.
Self Join Case-1: (when leftOuter or any other join is made with the same table then
that is also self join)
select [Link],
[Link],
[Link],
[Link],
[Link] as SupervisorFirstName,
[Link] as SupervisorLastName
from Employee e1
left outer join Employee e2 on [Link] = [Link]
NOTE:
While writing query for Self join , make the same table two times that will help in
writing query.
ImpNote:-
Self join can be achieved by Inne ,Left,Right,Outer Joins.
Explanation:-
Table t1,t2
Agr tou left table(t1) sa display karwa rahy cheezain aur left outer join lagaya hua tou result inner
join jaisa nahi aie ga but agr right outer join lagaya hua aur display left sa hi krwa rahy hue tou inner
join wala result hi aie ga kyu k unmatch of right return hooni hain prdisplay (t1) sa hour aha.
For Further([Link]
outer-join-not-retain-all-the-values)
6) CARTESIAN JOIN
The CARTESIAN JOIN or CROSS JOIN returns the Cartesian product of the sets of records
from two or more joined tables.
Note : (mtlb pehle row of table 1 ko table 2 ki saare rows k sath combine krke show kre ga
phr table 1 ki next row ko table 2 ki saare rows k sath)
Example:-
select empno,ename,job,dname ,loc from employee e,department d
where [Link]>[Link]
EQUI JOIN:
is a sub-category of INNER JOIN, here you only use Equal To operator “=”, like:
1. SELECT [Link], [Link], [Link], [Link]
2. FROM Employee E, Department D
3. WHERE [Link] = [Link]
Equi join:-
is a subcategory of inner join that can only have (=) operator.
Equi join can be an Inner join,Left Outer join, Right Outer join
Important Note:-
Inner , Outer , Left , Right , Self Uses Equi and Non-Equi joins in their
conditions.
Natural Join:-
A NATURAL JOIN is a JOIN operation that creates an implicit join clause for you based on the
common columns in the two tables being joined. Common columns are columns that have the
same name in both tables. A NATURAL JOIN can be an INNER join, a LEFT OUTER join, or a
RIGHT OUTER join. The default is INNER join.
Examples:-
Select [Link], [Link] from A a Natural (Left / Right) Join B b;
Note:-
As ON(used in Joins ) ,WHERE, HAVING are used to
specify condition. So they(teeno) can appear
simultaneously in a Single query.
For example, :-
imagine that you are joining the titles and publishers tables to create a query showing the
average book price for a set of publishers. You want to see the average price for only a specific
set of publishers - perhaps only the publishers in the state of California. And even then, you
want to see the average price only if it is over $10.00.
SELECT titles.pub_id, AVG([Link])
FROM titles INNER JOIN publishers
ON titles.pub_id = publishers.pub_id
WHERE [Link] = 'CA'
GROUP BY titles.pub_id
HAVING AVG(price) > 10
You must place (comparison operators) =, <>, <, >, <=, or >= operator before
ANY.
SELECT *
FROM employee
WHERE salary > ANY (2000, 3000, 4000);
But Before IN we cannot place any operator mtlb isme sirf (=) compare hoota;
SELECT *
FROM employee
WHERE salary IN (2000, 3000, 4000);
SQL Constraints
SQL constraints are used to specify rules for data in a table →are type of conditions
or restrictions.
Views:-
VIEWS are virtual tables that do not store any data of their own but display data
stored in other existing tables. In other words, VIEWS are nothing but SQL Queries.
A view can contain all or a few rows from a table. A MySQL view can show data from
one table or many tables.
Note:- (Agr hm aik View ma kch insert krte tou kya actual table ma bhi
wou changings aati)? ([Link]
original-table-get-affected)
Hence updating a view also results in update of main table.
When you insert any record in a VIEW it’ll get inserted in your main table too and
if you delete that record from VIEW the same record would be delete from table
too.
2. The view must include the PRIMARY KEY of the table based
upon which the view has been created.
3. The view should not have any field made out of aggregate
functions.
4. The view must not have any DISTINCT clause in its definition.
ADVANTAGES OF Views:
Security
Query Simplicity
Reusability
Views can hide the complexity of data. For example, a view could appear as Sales2000 or
Sales2001, transparently partitioning the actual underlying table.
Views take very little space to store; the database contains only the definition of a view,
not a copy of all the data that it presents.
Due to security, Data Integrity is also maintained.
This makes views useful for abstracting or hiding complex queries.
Disadvantage:
Performance :-Jaisa k usko aik Complex virtual table banana par raha hoota
na k actual table show krwana hota so performance low
Update restrictions.(Discussed above)
Create View
CREATE VIEW `view_name` AS SELECT statement;
Update View
CREATE OR REPLACE VIEW ‘Brazil Customers’ AS SELECT CustomerName,
ContactName
FROM Customers WHERE Country = 'Brazil';
Drop View
DROP VIEW ` View Name `;
Indexing:-
Indexing is a way to optimize the performance of a query on a Database by minimizing the
number of disk accesses required when a query is processed. It is a data structure technique
which is used to quickly locate and access the data in a database.
Clustered Index Syntax:-
CREATE CLUSTERED INDEX "Col1"
ON dbo."application" ("user_id");
Primary Index:-
When ever a table is created with a primary key then
automatically it will act as Primary Index.
Or:-
CREATE INDEX indexOfEmp ON emp(id)
Note:-
Indexes ka faida hi tb ha jb aap unko Queries ma use krou.
Advantages of Indexes:-
1. Searching For Records :- agr hm WHERE Clause ma index column ko mention karien
tou retrieval kaafi fast.
2. Sorting Records:-
Example:- SELECT * FROM Products ORDER BY UnitPrice ASC
Mtlb Agr hm ORDERBY ko aise column pr lagaien jis pr hmne Index create kiya hooga
tou Sorting will be very easy jaise k index table sorted way ma indexes store krta ha
3. Grouping Records:- SELECT Count(*), UnitPrice FROM Products GROUP BY UnitPrice
a. Agr hm GROUPBY ko aise column pr lagaien jis pr hmne Index create kiya hooga
tou GROUPING will be very easy jaise k index table sorted way ma indexes store
krta ha tou aik jaise prices waali cheezain aik sath hi pari houn gi tou grouping
faster.
Disadvantages of Indexes:-
1. Data Modification:- (INSERT , UPDATE , DELETE):-
i) Agr hm aik row DELETE krte tou agr us row ki koi value as an INDEX pari hui tou
usko bhi delete hoona pare ga INDEX table ma aur agr NON-Clustered Scene hua
tou saare INDEX Tables ko modify krna pare ga .Similarly with INSERT AND
UPDATE.
ii) UPDATE:- Agr tou koi aisa column update krien gy jo k INDEX ha tb costly warna nai
iii) Hence it hurts the performance of Data Modification.
2. Additional Disk Space:-
INDEX TABLES Disk per store hooty aur unka size Table and Type of Column (INDEX)
Dependent hoota ,tou unko store krne k liye extra space lgti
-: Transaction:-
☹ (ATM-machines uses transaction)
Transactions group a set of tasks into a single execution unit.
The effects of all the SQL statements( Set Of Tasks) in a
transaction can be either all committed (applied to the
database) or all rolled back (undone from the database , agr
tou kisi aik bhi task ma error aaya tou saare hi tasks
perform nai houn ge).
Atomicity: The 'all or nothing' property. (Ya tou saare task warna koi bhi nai)
Consistency:( (Data correct way Ma hooga aur constraints bhi followed hoi
houn gi )
Isolation: (Aik transaction ka effect doosri transaction pr ni aie ga)
Durability: (Database ma permanent effect aie ga after COMMIT).
SQL Injection:-
SQL injection is a code injection technique that might destroy your
database.
SQL injection is one of the most common web hacking techniques.
SQL injection is the placement of malicious code in SQL statements, via
web page input.
How it works:-
SQL injection usually occurs when you ask a user for input, like their
username/userid, and instead of a name/id, the user gives you an SQL
statement that you will unknowingly run on your database.
1) Input validation
2) Parametrized queries
3) Stored procedures
Triggers:-
A trigger is a set of actions or SQL-Statements in database which automatically
invokes whenever a special event in the database occurs. For example, a trigger can be
invoked when a row is inserted into a specified table or when certain table columns are
being updated.
Types of Triggers
This section describes the different types of triggers:
Syntax:
create trigger [trigger_name]
[before | after]
{insert | update | delete}
on [table_name]
[for each row]
[trigger_body]
Points To Ponder:-
Delete After Trigger(Jb kisi aik table ma kuch delete hou tou us event
pr kisi aur table ma kch insert krna)
DELIMITER
$$
CREATE TRIGGER `abc`
AFTER DELETE ON student FOR EACH ROW
BEGIN
INSERT into stlog VALUES (CONCAT('Update Student
Record’,[Link],' Clas :',OLD.ST_CLASS, '-> Deleted on ',
NOW()));
END;
$$
Before Update:-( Newly UpDating value must be in range)
mysql> delimiter //
mysql> CREATE TRIGGER upd_check BEFORE UPDATE ON account
FOR EACH ROW
BEGIN
IF [Link] < 0 THEN
SET [Link] = 0;
ELSEIF [Link] > 100 THEN
SET [Link] = 100;
END IF;
END;//
mysql> delimiter ;
After UpDate Trigger(Jb kisi aik table ma kuch Update hou tou us
event pr kisi aur table ma kch insert krna)
DELIMITER
$$
CREATE TRIGGER `abc`
AFTER Update ON student FOR EACH ROW
BEGIN
INSERT into stlog VALUES (CONCAT('Update Student
Record’,[Link],' Clas :',OLD.ST_CLASS, '-> Updated on ',
NOW()));
END;
$$
Before Insert (If there are any space(s) before or after the
FIRST_NAME, TRIM() function will remove those.)
DELIMITER
$$
CREATE TRIGGER `abc`
BEFORE INSERT
ON emp_details FOR EACH ROW
BEGIN
SET NEW.FIRST_NAME = TRIM(NEW.FIRST_NAME);
$$
DELIMITER
$$
CREATE
TRIGGER `abc`
AFTER INSERT ON `emp_details`
FOR EACH ROW
BEGIN
INSERT INTO log_emp_details
VALUES(NEW.employee_id, [Link], NOW());
END$$
Drop A Trigger :-
DROP TRIGGER ‘trigger name’;
Also
ALTER TRIGGER ‘abc’ ENABLE | DISABLE
ALTER TABLE ‘abc’ ENABLE | DISABLE ALL TRIGGERS
Delimeter:-
In SQL you close each statement with a delimiter, which is by default a semicolon (;). In a
trigger you need to write multiple statements, each ending in a semicolon. To tell MySQL
that those semicolons are not the end of your trigger statement, you temporarily change the
delimiter from ; to //, so MySQL will know that the trigger statement only ends when it
econunters a //.
DELIMITER
//
SYNTAX:-
Call Above:-
SELECT
order_id,
SUM([Link](quantity, list_price, discount)) net_amount
FROM
sales.order_items
GROUP BY
order_id
ORDER BY
net_amount DESC;
OR:-
SELECT
[Link](10,100,) net_sale;
Calling Above:-
SELECT
*
FROM
udfProductInYear(2017);
Advantages Of Functions:-
They can be used in SELECT , WHERE, CASE statements.
Table Valued Functions can also work like Parametrized
Views
Disadvantage:-
They Cannot call Stored Procedure.
They allow only SELECT Statement on Database.
We cannot return more than one value from function
We cannot use print statement inside function
We cannot use try catch inside a function
END AS QuantityText
FROM OrderDetails;
Schedulars:-
The Scheduler enables us to control when and where various tasks take place in
the database environment. These tasks can be time consuming and complicated, so using
the Scheduler can help you to improve the management and planning of these tasks.
Examples:-
Agr tou hm chahty houn k yaar raat ko bara bje ma kisi aik particular table koi particular
operation automatically perform hou jaie tou app wu operation Schedule kr daity hou
Parallel transactions management
Types:-
1) Serial Schedule:-
Jb tk Aik Transaction /Task khatm nai hoo jata doosra Task /Transaction start
bhi nai hou ga
2) Non-Serial Schedule:-
Aik Transaction /Task k khatm hoony sa pehly doosra task start ya donou ma
Contact Switching hooti rahy
a. Strict
Agr aik transaction na aik table pr Read perform kiya aur usky
foran baad 2nd transaction ushi table pr Read perform krti tou ab
2nd transaction apna write tb tk nai kr sakti jb tk transaction 1
apna Write commit nai kr aiti.
Ta Tb
----- -----
R(X)
R(X)
W(X)
commit
W(X)
R(X)
commit
b. Cascadeless
Agr aik transaction kisi value per Write
perform karahi ha aur 2nd transaction ushi
value pr Read()/Write() perform krna chahti
ha tou usko wait krna hooga jb tk
Transaction 1 apna Write() operation
commit na kr la
Ta Tb
----- -----
R(X)
W(X)
W(X)
commit
R(X)
W(X)
commit
c. Recoverable
Isme aik transaction ye faisla kr aiti ha k ma apne app ko tb tk
commit nai kru gi jb tk k baaqi transactions apne app ko commit
nai kr laity. Iska faida ye ha k agr ye saari transactions aik hi data
pr kaam kr rahi houn tou us transaction k paas ye Power hooti k
agr tou baaqi transactions ki perform ki hui changings usko
pasand nai aien tou wou poorani state of data ko Recover kr sakti
T1 T2
R(A)
W(A)
W(A)
R(A)
commit
commit
ER-Diagram:-
It is a Graphical Representation of Entities(Tables /
Objects) in a Database and Relationship between Them.
Advantages:
Database k banene sa pehle hi errors remove , relation
ships defined For Example Ghar Banene sa pehle naqsha
banaya jata
Entity / Object :-
Any that has a physical existence.
Weak Entity:
An entity that cannot be uniquely identified by its own attributes and relies on the
relationship with other entity is called weak entity.
For example Bank Account Entity can not survive without Bank Entity
Attributes:-(
That represents the characteristics of an Object
Representation of:
Entity: In Rectangle.
Attribute:- In Oval.
Relationships:- In Diamond.
Cardinality:- one to one , one to many , many to
many (type of relationship b/w entities)
Connecting Lines:- Straight Lines
Stored Procedures:-
A stored procedure is a prepared SQL code that you can save, so the code can
be reused over and over again.
So if you have an SQL query that you write over and over again, save it as a
stored procedure, and then just call it to execute it.
You can also pass parameters to a stored procedure, so that the stored
procedure can act based on the parameter value(s) that is passed.
END
Above code ko execute krne (sql window ma
execute krne ka tareeqa)
Declare @id1 int
print @id1
Procedure without transactions
CREATE PROCEDURE abc(@id int)
AS
BEGIN
SET NOCOUNT ON;
insert into talha(id) values(@id)
END
GO
How to call above procedure:-
exec abc @id=4
Advantages of the stored procedure
Reusable and Transparent to any application.
Secure.
Reduce the data traffic between the application and database server.
Increase the performance of the application.
-Disadvantages of the Stored procedure.
A large number of Logical operations increase CPU usage.
Difficult to Debug.
Not easy to Develop and Maintain.
Not designed for developing Complex or Flexible business logic.
Too much overhead is incurred from maintaining Stored Procedures
that are not complex enough. As a result, the general consensus is
that simple SELECT statements should not be bound to Stored
Procedures and instead implemented as inline SQL
What is Normalization?
NORMALIZATION is a database design technique that organizes tables in a manner
that reduces redundancy and dependency of data. Normalization divides larger
tables into smaller tables and links them using relationships. The purpose of
Normalization is to eliminate redundant (useless) data and ensure data is stored
logically.
Advantages of Normalization:-
1) Updates run quickly due to no data being duplicated in multiple locations
2) Inserts run quickly since there is only a single insertion point for a piece of data and no
duplication is required.
Denormalization in Databases
Denormalization is a database optimization technique in which we add redundant data
to one or more tables. This can help us avoid costly joins in a relational database. Note
that denormalization does not mean not doing normalization. It is an optimization
technique that is applied after doing normalization.
Super Key:-
It is SET that contains all Candidate Keys
Composite Key:-
A Primary Key build upon more than 1 Column to uniquely
identify records.
Candidate Keys:-( Subset of SuperKey)
Hamare paas aik sa zaada options hou sakti k hm kis column ko
Primary key [Link] aise tamam options Candidate Keys
hooty
Alternate Keys:-
Jp primary key select hou jaie gi tou jo options candidate keys ki
reh jaien gi wou houn ALTERNATE keys
NoSql Sql
They can store data either in They store in tables having
keyValue Pair , Graph like relations with each other
structure , Document(Tree) like
structure
Select Max([Link]) from Workers w1, Workers w2, Workers w3, Workers w4, Workers w5
Where [Link]> [Link] AND [Link] > [Link] AND [Link]> [Link] AND [Link] > [Link]
Use the following generic method to find nth highest salary without
using TOP or limit.
SELECT Salary
FROM Worker W1
WHERE n-1 = (
FROM Worker W2