Skip to content

Commit 5b7f8ce

Browse files
committed
Added indexes, loops, transactions, trigger
1 parent ce0a8e0 commit 5b7f8ce

File tree

8 files changed

+391
-0
lines changed

8 files changed

+391
-0
lines changed

Indexes/Examples.sql

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
-- CREATE INDEX
2+
3+
-- Syntax
4+
5+
CREATE INDEX index_name
6+
ON table_name (column1, column2, ...);
7+
8+
-- Example
9+
10+
CREATE INDEX idx_Orders_CustomerID
11+
ON Orders (CustomerID);
12+
13+
-- Now we can do faster queries by CustomerID
14+
15+
SELECT OrderID, OrderDate
16+
FROM Orders
17+
WHERE CustomerID = 'ALFKI';
18+
19+
20+
-- DROP INDEX
21+
22+
-- Syntax
23+
24+
DROP INDEX table_name.index_name;
25+
26+
-- Example
27+
28+
DROP INDEX Orders.idx_Orders_CustomerID;

Indexes/README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Indexes
2+
3+
Indexes are used for faster reach to data and the users can't see the indexes.
4+
5+
![img1](https://i.ytimg.com/vi/YuRO9-rOgv4/maxresdefault.jpg)

Loops/Examples.sql

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
-- WHILE LOOP
2+
3+
-- Syntax
4+
5+
WHILE <condition>
6+
SQL Statement | statement_block | BREAK | CONTINUE
7+
8+
9+
-- Example 1
10+
11+
DECLARE @i INT = 1;
12+
13+
WHILE @i <= 5
14+
BEGIN
15+
PRINT(@i);
16+
SET @i = @i + 1;
17+
END;
18+
19+
-- Example 2
20+
21+
CREATE PROCEDURE CountOrders
22+
@EmployeeID INT,
23+
@OrderCount INT OUTPUT
24+
as
25+
BEGIN
26+
SET @OrderCount = 0;
27+
28+
DECLARE @CurrentOrderID INT, @CurrentEmployeeID INT; -- New local variables
29+
30+
DECLARE order_cursor CURSOR FOR
31+
SELECT OrderID, EmployeeID
32+
FROM Orders; -- Creating order_cursor for choosing per row in orders
33+
34+
OPEN order_cursor;
35+
36+
FETCH NEXT FROM order_cursor
37+
INTO @CurrentOrderID, @CurrentEmployeeID; -- Opening order_cursor for taking first row and setting orderID and employeeID to our variables from current row
38+
39+
WHILE @@FETCH_STATUS = 0 -- If fetch is success
40+
BEGIN
41+
IF @CurrentEmployeeID = @EmployeeID
42+
BEGIN
43+
SET @OrderCount = @OrderCount + 1;
44+
END;
45+
46+
FETCH NEXT FROM order_cursor
47+
INTO @CurrentOrderID, @CurrentEmployeeID;
48+
END;
49+
50+
CLOSE order_cursor;
51+
DEALLOCATE order_cursor;
52+
END;
53+
54+
55+
-- Test
56+
57+
DECLARE @OrderCount INT;
58+
59+
EXEC
60+
CountOrders 4,
61+
@OrderCount OUTPUT;
62+
63+
SELECT @OrderCount as 'Order Count';
64+
65+
66+
-- We can too do this as
67+
SELECT COUNT(*) as 'Order Count'
68+
FROM Orders
69+
WHERE EmployeeID = 4;

Loops/README.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# Loops
2+
3+
Loops are the technique where a set of SQL statements are executed repeatedly until a condition is met.
4+
5+
![img1](https://s33046.pcdn.co/wp-content/uploads/2019/10/flow-chart-of-the-sql-while-loop-1.png)

Transactions/Examples.sql

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
-- Transaction Expressions
2+
3+
-- BEGIN TRANSACTION -> starting a new transaction.
4+
-- COMMIT -> makes all changes in the transaction permanent.
5+
-- ROLLBACK -> rolls back all changes in the transaction since start. If a error occured or transaction is not completed, used ROLLBACK expression.
6+
7+
-- Example
8+
9+
BEGIN TRANSACTION;
10+
11+
UPDATE Products
12+
SET UnitsInStock = UnitsInStock - 5
13+
WHERE ProductID = 1;
14+
15+
IF @@ERROR = 0
16+
COMMIT;
17+
ELSE
18+
ROLLBACK;
19+
20+
21+
-- Example 2
22+
23+
BEGIN TRANSACTION;
24+
25+
BEGIN TRY
26+
INSERT INTO Orders (CustomerID, EmployeeID, OrderDate)
27+
VALUES ('VINET', 5, GETDATE())
28+
29+
DECLARE @NewOrderID INT;
30+
SELECT @NewOrderID = SCOPE_IDENTITY()
31+
32+
INSERT INTO [Order Details] (OrderID, ProductID, UnitPrice, Quantity, Discount)
33+
VALUES (@NewOrderID, 3, 15, 3, 0)
34+
35+
COMMIT;
36+
END TRY
37+
BEGIN CATCH
38+
ROLLBACK;
39+
40+
PRINT ERROR_MESSAGE();
41+
END CATCH;

Transactions/README.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# Transactions
2+
3+
In SQL, a process (transaction) is that grouping one or more sql statements as one statemenet. Transactions ensure that statements are performed correctly and error management.
4+
5+
## 4 Features of Transactions (ACID)
6+
- **Atomicity:** A transaction is completely successes or never successes. If there is a error in any transaction, transaction is not completed and all changes in the database are rolled back.
7+
- **Consistency:** Each transaction is moves the database from one consistent state to another. So a transaction complies with rules of the database before and after.
8+
- **Isolation:** Concurrent processes are isolated from each other. The results of a transaction are not visible to other transactions until the transaction is complete.
9+
- **Durability:** After a transaction is completed, the results of the transaction are permanent and are not lost even in the event of a system failure.
10+
11+
![img1](https://f4n3x6c5.stackpathcdn.com/UploadFile/f0b2ed/transaction-management-in-sql/Images/Transaction%20Control.jpg)

Triggers/Examples.sql

Lines changed: 222 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,222 @@
1+
-- DML Triggers
2+
-- CREATE TRIGGER
3+
--Syntax
4+
5+
CREATE TRIGGER trigger_name
6+
ON table_name
7+
{FOR | AFTER | INSTEAD OF} {[INSERT] [,] [UPDATE] [,] [DELETE]}
8+
AS
9+
{sql_statements}
10+
11+
-- Example 1
12+
13+
CREATE TRIGGER NewOrderTrigger
14+
ON Orders
15+
AFTER INSERT
16+
as
17+
BEGIN
18+
PRINT 'A new order has been placed.';
19+
END;
20+
21+
-- Users when add a data to the orders will see print message
22+
23+
24+
-- Example 2
25+
26+
-- Procedure
27+
CREATE PROCEDURE GetProductByID
28+
(
29+
@ProductID INT
30+
)
31+
as
32+
BEGIN
33+
SELECT ProductID,
34+
ProductName,
35+
UnitsInStock
36+
FROM Products
37+
WHERE ProductID = @ProductID
38+
END;
39+
40+
CREATE PROCEDURE DecraseStock
41+
(
42+
@ProductID INT,
43+
@Quantity INT
44+
)
45+
as
46+
BEGIN
47+
UPDATE Products
48+
SET UnitsInStock = UnitsInStock - @Quantity
49+
WHERE ProductID = @ProductID
50+
END;
51+
52+
-- Trigger
53+
CREATE TRIGGER UpdateStock
54+
ON [Order Details]
55+
AFTER INSERT
56+
as
57+
BEGIN
58+
DECLARE @Product INT
59+
DECLARE @Qty INT
60+
61+
SELECT @Product = ProductID,
62+
@Qty = Quantity
63+
FROM INSERTED;
64+
65+
EXEC DecraseStock
66+
@ProductID = @Product,
67+
@Quantity = @Qty
68+
69+
EXEC GetProductByID
70+
@ProductID = @Product
71+
END;
72+
73+
-- Test
74+
INSERT INTO [Order Details]
75+
(
76+
OrderID,
77+
ProductID,
78+
Quantity,
79+
UnitPrice
80+
)
81+
VALUES
82+
(
83+
10501,
84+
2,
85+
1,
86+
5
87+
)
88+
89+
90+
-- ALTER TRIGGER
91+
-- Syntax
92+
93+
ALTER TRIGGER trigger_name
94+
ON table_name
95+
{FOR | AFTER | INSTEAD OF} {[INSERT] [,] [UPDATE] [,] [DELETE]}
96+
AS
97+
{sql_statements}
98+
99+
-- Example
100+
ALTER TRIGGER UpdateStock
101+
ON [Order Details]
102+
AFTER INSERT
103+
as
104+
BEGIN
105+
DECLARE @Product INT
106+
DECLARE @Qty INT
107+
108+
SELECT @Product = ProductID,
109+
@Qty = Quantity
110+
FROM INSERTED;
111+
112+
EXEC DecraseStock
113+
@ProductID = @Product,
114+
@Quantity = @Qty
115+
END;
116+
117+
118+
-- Now lets update the UpdateStock to more complex
119+
120+
-- 1 more procedure
121+
CREATE PROCEDURE IncreaseStock
122+
(
123+
@ProductID INT,
124+
@Quantity INT
125+
)
126+
as
127+
BEGIN
128+
UPDATE Products
129+
SET UnitsInStock = UnitsInStock + @Quantity
130+
WHERE ProductID = @ProductID
131+
END;
132+
133+
-- Now updating our trigger to insert and delete events cause actived the trigger
134+
135+
ALTER TRIGGER UpdateStock
136+
ON [Order Details]
137+
FOR INSERT, DELETE
138+
as
139+
BEGIN
140+
DECLARE @insertedProduct INT, @insertedQty INT, @deletedProduct INT, @deletedQty INT
141+
142+
SELECT @insertedProduct = ProductID,
143+
@insertedQty = Quantity
144+
FROM INSERTED;
145+
146+
SELECT @deletedProduct = ProductID,
147+
@deletedQty = Quantity
148+
FROM DELETED;
149+
150+
IF @insertedProduct IS NOT NULL
151+
BEGIN
152+
EXEC DecraseStock
153+
@ProductID = @insertedProduct,
154+
@Quantity = @insertedQty
155+
156+
EXEC GetProductByID
157+
@ProductID = @insertedProduct
158+
END;
159+
160+
IF @deletedProduct IS NOT NULL
161+
BEGIN
162+
EXEC IncreaseStock
163+
@ProductID = @deletedProduct,
164+
@Quantity = @deletedQty
165+
166+
EXEC GetProductByID
167+
@ProductID = @deletedProduct
168+
END;
169+
END;
170+
171+
-- Test
172+
-- Insert
173+
INSERT INTO [Order Details]
174+
(
175+
OrderID,
176+
ProductID,
177+
Quantity,
178+
UnitPrice
179+
)
180+
VALUES
181+
(
182+
10503,
183+
2,
184+
1,
185+
5
186+
)
187+
188+
-- Delete
189+
DELETE FROM [Order Details]
190+
WHERE OrderID = 10503 AND ProductID = 2;
191+
192+
193+
-- DROP TRIGGER
194+
DROP TRIGGER UpdateStock
195+
196+
197+
-- DDL Trigger Example
198+
199+
CREATE TRIGGER PreventTableCreation
200+
ON example
201+
FOR CREATE_TABLE
202+
AS
203+
BEGIN
204+
PRINT 'You cannot create a table in this database.';
205+
ROLLBACK;
206+
END;
207+
208+
209+
-- LOGON Trigger Example
210+
211+
CREATE TRIGGER RestrictLogon
212+
ON ALL SERVER WITH EXECUTE AS 'sa'
213+
FOR LOGON
214+
AS
215+
BEGIN
216+
IF ORIGINAL_LOGIN() != 'sa' AND ORIGINAL_LOGIN() != 'dbo'
217+
BEGIN
218+
PRINT 'You cannot access this database.';
219+
ROLLBACK;
220+
END
221+
END;
222+

Triggers/README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
# Triggers
2+
3+
An SQL Trigger is database object that is associated with a table. A trigger is automatically invokes whenever a special event in the database occurs.
4+
5+
## Different Types of Triggers
6+
- **DDL Trigger:** The Data Definition Language (DDL) command events such as Create Table, Create View, Drop Table, Drop View and Alter Table cause the DDL Triggers to be activated.
7+
- **DML Trigger:** The Data Manipulation Language (DML) command events that begin with Insert, Update and Delete set off the DML Triggers.
8+
- **Logon Triggers:** Logon triggers are fires in response to a LOGON event. When a user session is created with a SQL Server instance after the authentication process of logging is finished but before establishing a user session, the LOGON event takes place.
9+
10+
![img1](https://d1jnx9ba8s6j9r.cloudfront.net/blog/wp-content/uploads/2019/10/Triggers-in-SQL.png)

0 commit comments

Comments
 (0)