0% found this document useful (0 votes)
60 views33 pages

SQL Joins and Data Manipulation Guide

Uploaded by

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

SQL Joins and Data Manipulation Guide

Uploaded by

Abdul Rahman
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

ORDER BY: it sorts in ASCENDING order by Default.

DELETE FROM CUSTOMERS


WHERE ID = 6; //Delete Row

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.

RollNo=Primary-Key RollNo=Foreign Key


RollNo Name Joining Course Id RollNo
025 Talha Tables 1 025
023 ali 1 023

1) SQL INNER JOIN Keyword


Inner Join only combines that data that has match values 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:

Display courseId , Name ,rollNO using both Above tables

Select [Link] , [Link] , [Link] FROM T1 a INNER

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

3)SQL RIGHT JOIN Keyword


The RIGHT JOIN keyword returns all records from the right table (table2), and
the matched records from the left table (table1). The result is NULL from the
left side, when there is no match.
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

Example-1:-The following SQL statement will return all employees, and


any orders they might have placed☹( upper left outer join waali ma
employee ko right table bana dou aur right outer join laga dou)

Example
SELECT [Link], [Link], [Link]
FROM Orders
RIGHT JOIN Employees ON [Link] = [Link]
ORDER BY [Link];

Note: In some databases RIGHT JOIN is called RIGHT OUTER JOIN.

4)SQL FULL OUTER JOIN Keyword


Full OUTER JOIN return all(Matched and unmatched )data from both tables,

Actually it combines the result of Left and Right outer join.

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.

Q)Self joins. Does Inner, Outer, or Left matter?


Yes, the output can be different for each join used in a self join.

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)

SELECT table1.column1 , table1.column2, table2.column1...


FROM table1
CROSS JOIN table2;

Non Equi Join:-


It is a sql join condition which makes use of some comparison operator other than the
equal sign like >, <, >=, <=, BETWEEN( AND )

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]

Difference between equi and inner join:-


INNER JOIN: Here you can JOIN two tables with various operators, like:

1. Equal To, “=”


2. Not Equal To, “<>”
3. Greater/Less Than, “>”, “<”,<=, etc.
4. BETWEEN(a AND b)

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

First ON, then WHERE , then Having is executed.


Note:-
Group By having k baghair use ho sakta ha ,having bhi group by k baghiar use hoo sakta pr phr
uska result sahi aie ga k nai no guruntee.

What is the difference between IN and ANY operators in


SQL?

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

They can be added on creation or after creation of table using Alter:

 NOT NULL - Ensures that a column cannot have a NULL value


 UNIQUE - Ensures that all values in a column are different
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely
identifies each row in a table
 FOREIGN KEY - Uniquely identifies a row/record in another table
 CHECK - Ensures that all values in a column satisfies a specific condition
 DEFAULT - Sets a default value for a column when no value is specified
 INDEX - Used to create and retrieve data from the database very quickly

CREATE TABLE Orders (


OrderID int NOT NULL,
City varchar(255) DEFAULT 'Sandnes',
PersonID int,Age int,
CHECK (Age>=18),
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

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.

When can a view be updated?(Update View mtlb actual

table ko update krna)

1. The view is defined based on one and only one table.

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

Updating a Column of a view( if a view satisfies the Updating


conditions then following is the way of updating column of a View)
UPDATE viewName SET columnName=’asda’ WHERE
condition.

View Stored Procedure

1 Does not accepts parameters Accept parameters


2 Can be used as a building block in large Can not be used as a building
query. block in large query.
3 Can contain only one single Select query. Can contain several statement like
if, else, loop etc.
4 Can not perform modification to multiple Can perform modification to one
tables. or several tables.
5 Can be used (sometimes) as the target for Can not be used as the target for
Insert, update, delete queries. Insert, update, and delete
queries.

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");

Secondary/Non Clustered Index:-


CREATE NONCLUSTERED INDEX "Col1"
ON dbo."application" ("user_id");

Secondary/Non Clustered Index: - (With Multiple Columns):-

CREATE NONCLUSTERED INDEX IX_Address_PostalCode


ON [Link] (PostalCode)
INCLUDE (AddressLine1, AddressLine2, City, StateProvinceID);

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)

Difference between primary key and Index?


 Primary key uniquely Identifies a row , and can be used as an
index value
 Index is used for the fast retrieval from the database and every
Index value is not tend to be a Primary key of the table.

Note: - Searching record in a table that has no index is much slower


than the searching in the table having an index column

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.

4. Maintaining a Unique Column:- CREATE UNIQUE


INDEX IDX_ProductName On Products (ProductName)
a. Ab agr user row add krty hue agr (ProductName) agr koi redundant value daalne
lage gi tou DATABASE INDEXING ki waja sa is cheez ko makesure kare ga k koi
redundant value na jaie.

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

Properties Of Transaction☹ (ACID-properties)

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

SQL injection protection: conclusion


Following techniques should be used to avoid Injections:

1) Input validation

2) Parametrized queries

 $stmt = $conn->prepare("INSERT INTO MyGuests (firstname)


VALUES (?)");
$stmt->bind_param("sss", $firstname);

// set parameters and execute


$firstname = "John";
$stmt->execute();

3) Stored procedures

Difference between unique and primary key


you can have many UNIQUE constraints per table, but only one PRIMARY KEY
constraint per table.

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.

Special Events:- Insert , Update , Delete

Types of Triggers
This section describes the different types of triggers:

 Row Triggers and Statement Triggers


 BEFORE and AFTER Triggers
INSTEAD OF Triggers( ye wou triggers jo hame Actual (Insert Update ,Delete) operations ko
Database pr apply hoony sa bachne ma madad krty)
 Triggers on System Events and User Events

Syntax:
create trigger [trigger_name]
[before | after]
{insert | update | delete}
on [table_name]
[for each row]
[trigger_body]

Points To Ponder:-

 In an INSERT trigger, only NEW.col_name can be used.

 In a UPDATE trigger, you can use OLD.col_name to refer to the columns of


a row before it is updated and NEW.col_name to refer to the columns of
the row after it is updated.

 In a DELETE trigger, only OLD.col_name can be used; there is no new row

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);
$$

AFTER INSERT Trigger:-


To insert some information into log_ emp_details every time,
when an INSERT happen into emp_details table .

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

Alter Trigger :- (it is used to enable or disable triggers associated with a


table)
Alter trigger [trigger_name]
[before | after]
{insert | update | delete}
on [table_name]
[for each row]
[trigger_body]

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

Advantages of using Triggers:-

 Control Update of data


 Control queries(Using INSTEAD OF )triggers
 Triggers are used for calling stored procedures
 Control Validation of data
 Resuability.
 Triggers provide another way to check the integrity of data(Complete ,
accurate,valid)

Disadvantages of using Triggers:-


 Triggers run every time when the database fields are updated and it is overhead
on system. It makes system run slower.
 Triggers execute invisible to client-application application. They are not visible or
can be traced in debugging code.
 Using Triggers we are adding business logic in database which is not desirable.

What is Business Logic:-


 Business logic is the programming that manages communication between an end user
interface and a database.
 Mtlb data k upper jo hm khud sa operations perform krty validation ya customization k liye
wou hoti business logic.

What is Referential Integrity:-


Referential integrity refers to the accuracy and consistency of data within a
relationship. In relationships, data is linked between two or more tables. ...
So, referential integrity requires that, whenever a foreign key value is used it must
reference a valid, existing primary key in the parent table.
FUNCTIONS:-

TWO Types Of Functions In Database☹


Path (Database ->Programability->StProc,Functions)
1)What are scalar functions
 SQL Server scalar function takes one or more parameters and returns a single
value.
 The scalar functions help you simplify your code. For example, you may have a
complex calculation that appears in many queries. Instead of including the
formula in every query, you can create a scalar function that encapsulates the
formula and uses it in each query.

SYNTAX:-

CREATE OR ALTER FUNCTION udfNetSale(


@quantity INT,
@price INT,
)
RETURNS DEC(10,2)
AS
BEGIN
RETURN @quantity * @price;
END;

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;

2)What is a table-valued function in SQL Server


 A table-valued function is a user-defined function that returns data of a table
type. The return type of a table-valued function is a table, therefore, you can use
the table-valued function just like you would use a table.
 Mtlb ye jahan use hoota wahan aik poora table return hoo jata.

CREATE FUNCTION udfProductInYear (


@model_year INT
)
RETURNS TABLE
AS
RETURN
SELECT
*
FROM
[Link]
WHERE
model_year = @model_year;

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

The SQL CASE Statement(IF-THEN-ELSE)


SELECT OrderID, Quantity,

CASE WHEN Quantity > 30 THEN 'quantity is greater'

WHEN Quantity = 30 THEN 'The quantity is 30'

ELSE 'The quantity is under 30'

END AS QuantityText

FROM OrderDetails;

Difference in stored proc and function:-


 The function must return a value but in Stored Procedure it is
optional. Even a procedure can return zero or n values.
 Functions can have only input parameters for it whereas
Procedures can have input or output parameters.
 Functions can be called from Procedure whereas Procedures
cannot be called from a Function
 Example:-
As inside select statement function can be called.
 The procedure allows SELECT as well as
DML(INSERT/UPDATE/DELETE) statement in it whereas Function
allows only SELECT statement in it.
 Procedures cannot be utilized in a SELECT statement whereas
Function can be embedded in a SELECT statement.
 We can use Transactions in Procedure whereas we can't use
Transactions in Function.

Differences between a Stored Procedure and


a Trigger:-
1. We can execute a stored procedure whenever we want with the help of the exec command, but a
trigger can only be executed whenever an event (insert, delete, and update) is fired.
2. Stored procedure can take input parameters, but we can't pass parameters as input to a trigger.
3. Stored procedures can return values but a trigger cannot return a value.
4. We can use Print commands inside a stored procedure for debugging purposes but we can't use
print commands inside a trigger.
5. We can use transaction statements like begin transaction, commit transaction, and rollback inside a
stored procedure but we can't use transaction statements inside a trigger.
6. We can use Print commands inside a stored procedure for debugging purposes but we can't use
print commands inside a trigger.

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.

How Schedular is made in SQL-Server:-


Sql Server Agent -> Jobs -> Create new Job -> Define name-> Define steps -> Define
Schedule

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

Difference b/w schema and erd:


A schema diagram is a diagram which contains entities and the attributes
that will define that schema. A schema diagram only shows us the
database design whereas erd shows the relationship b/w those entites.
Ek esi diagram jis m bs entities aur attributes hte jo is schema ko define
krty h db design actually hoga kia jb k erd un entites k darmian relation ko
describe krta hai k relation kis type ka h r kin kin entities k darmian hai.

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.

Stored Procedure with Transaction and


Output Parameters(Jahan insertion k baad jo id assign
hooni wou return krahe):-

CREATE PROCEDURE abc


@id INT OUTPUT
@empId INT
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRANSACTION

SELECT @id = id(column name of


table)
FROM talha WHERE EmployeeID =
@empId

COMMIT TRAN -- Transaction Success!


END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRAN
END CATCH

END
Above code ko execute krne (sql window ma
execute krne ka tareeqa)
Declare @id1 int

exec abc @id(jo column wahan pr output


hona)=@id1 out,2nd parameter ki val

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.

1NF (First Normal Form) Rules


 Each table cell should contain a single value.
 Each record needs to be unique.(mtlb 2 same rows na houn)

2NF (Second Normal Form) Rules


 Rule 1- Be in 1NF
 Rule 2- Single Column Primary Key

3NF (Third Normal Form) Rules


 Rule 1- Be in 2NF
 Rule 2- Has no transitive functional dependencies (A transitive functional
dependency is when changing a non-key column, might cause any of the
other non-key columns to change)

BCNF (Boyce-Codd Normal Form)


Even when a database is in 3rd Normal Form, still there would be anomalies
resulted if it has more than one Candidate Key.

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.

3) Fewer indexes per table ensures faster maintenance tasks

4) Less data redundancy

5) Data Integerity will be there.


DrawBacks of Normalization:-
1. Due to mare tables larger work is required to get data as JOINS will
be used so A Costly work

2. Performance of system will be reduced as tables will be


containing codes rather than real data

3. Query will become difficult and complex

4. Requires Detailed Analysis and Design, Normalizing a


database is a complex and difficult task

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

How Foreign Have Redundant Values:-


EmpId(PK) DeptId(FK)
1 1 As dept can be same
for both
2 1

Q) What are the SQL Statements used:


 DDL
 DML
 DCL
Q #12) Enlist some commands of DDL, DML, and DCL.(Following ae the 3 SQL
Statements )
Ans: Data Definition Language (DDL) commands:
 CREATE to create a new table or database.
 ALTER for alteration.
 Truncate to delete data from the table.
 DROP to drop a table.
 RENAME to rename a table.
Data Manipulation Language (DML) commands:
 Select
 INSERT to insert a new row.
 UPDATE to update an existing row.
 DELETE to delete a row.
 MERGE for merging two rows or two tables.
Data Control Language (DCL) commands:
 COMMIT to permanently save.
 ROLLBACK to undo the change.
 SAVEPOINT to save temporarily.

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

 Horizontally scalable( Adding more  Vertically scalable( adding more


buildings in neighbours) floors to same building)

 Handles more load of data  Handles less load than No-Sql

 Much faster  Less faster

 No predefined structure  Predefined structure


 Not good for complex queries  Good for complex queries

Q-34. Write An SQL Query To Determine The 5th Highest Salary


Without Using TOP Or Limit Method.

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

SELECT COUNT( DISTINCT ( [Link] ) )

FROM Worker W2

WHERE [Link] >= [Link]);

You might also like