Download presentation
Presentation is loading. Please wait.
1
Database practice session
Hassan Tariq 5/5/2018 Database practice session Hassan Tariq MCP – Software LUMS/FAST/UCP Hassan Tariq
2
Introduction to database
DATABASE: Collection of related data. DMBS: A database management system (DBMS) is a collection of programs that enables you to store, modify, and extract information from a database. BENEFITS: Controlling Redundancy, Restricting Unauthorized Access, Providing Persistent Storage for Program Objects, Providing Multiple User Interfaces, Search Techniques for Efficient Query Processing Hassan Tariq – TRG /FAST NUCES / LUMS
3
Important Keywords Schema: The description of a database.
Metadata: The structural components of tables and their elements. For example data types, name of data and size. Key - One or more columns in a database table that is used to identify rows in a table Hassan Tariq – TRG /FAST NUCES / LUMS
4
KEYS Primary key. A primary key is a one or more fields that uniquely identifies a row in a table. Foreign key. A foreign key is a relationship between columns in two database tables designed to insure consistency of data Candidate key. A candidate key is a column or group of columns that can uniquely identify a row in the table without referring to any other source. Surrogate key. A primary key which is internally generated (typically auto-incremental integer value) that does not exist in the real world Hassan Tariq – TRG /FAST NUCES / LUMS
5
Introduction to SQL What is SQL?
When a user wants to get some information from a database file, he can issue a query. The user specifies a certain condition. The program will go through all the records in the database file and select those records that satisfy the condition. The result of the query will then be stored in form of a table. Hassan Tariq – TRG /FAST NUCES / LUMS
6
SQL - QUERY Hierarchy Hassan Tariq 5/5/2018 Hassan Tariq
Data Definition Language - DDL Create/alter/drop Data Manipulation Language - DML Insert/delete/update Transact-SQL - TSQL a sequence of SQL statements Hassan Tariq – FAST NUCES Hassan Tariq
7
SQL Query HIERARCHY SELECT FROM WHERE GROUP BY HAVING ORDER BY
Hassan Tariq SQL Query HIERARCHY SELECT FROM WHERE GROUP BY HAVING Transparent 3-D steps with labels (Advanced) To reproduce the bottom rectangle shape with text effects on this slide, do the following: On the Home tab, in the Slides group, click Layout, and then click Blank. On the Home tab, in the Drawing group, click the More arrow on the Shapes gallery, and then under Rectangles, click Rectangle (first option from the left). On the slide, drag to draw a rectangle. Under Drawing Tools, on the Format tab, in the Size group, do the following: In the Shape Height box, enter 1.5”. In the Shape Width box, enter 3”. On the Home tab, in the bottom right corner of the Drawing group, click the Format Shape dialog box launcher. In the Format Shape dialog box, click Fill in the left pane, and then do the following in the right pane: Select Solid fill. Click the button next to Color, and then under Theme Colors click White, Background 1 (first row, first option from the left). In the Transparency box, enter 0%. Also in the Format Shape dialog box, click Line Color in the left pane, and then select No line in the right pane. Also in the Format Shape dialog box, click 3-D Rotation in the left pane. In the right pane, click the button next to Presets, and then under Parallel click Off Axis 2 Top (third row, second option from the left). Also in the Format Shape dialog box, click 3-D Format in the left pane, and then do the following in the right pane: Under Bevel, click the button next to Top, and then under Bevel click Circle (first row, first option from the left). Next to Top, in the Width box, enter 7 pt, and in the Height box, enter 7 pt. Under Depth, click the button next to Color, and then under Theme Colors click White, Background 1 (first row, first option from the left). In the Depth box, enter 40 pt. Under Surface, click the button next to Material, and then under Translucent click Clear (third option from the left). Click the button next to Lighting, and then under Special click Two Point (second option from the left). In the Angle box, enter 70°. On the Insert tab, in the Text group, click Text Box, and then on the slide, drag to draw the text box. On the Home tab, in the Paragraph group, click Align Text Right to align the text right on the slide. Enter text in the text box, select the text, and then on the Home tab, in the Font group, select TW Cen MT Condensed from the Font list and then select 36 from the Font Size list. Under Drawing Tools, on the Format tab, in the WordArt Styles group, click the arrow next to Text Fill, and then under Theme Colors click White, Background 1 (first row, first option from the left). Drag the text box and position it over the rectangle. In the Format Text Effects dialog box, click 3-D Rotation in the left pane. In the right pane, click the button next to Presets, and then under Parallel click Off Axis 2 Left (second row, fourth option from the left). Select the text box. Under Drawing Tools, on the Format tab, click Text Effects, then point to 3-D Rotation, and then click 3-D Rotation Options. To reproduce the background on this slide, do the following: Right-click the slide background area, then click Format Background. In the Format Background dialog box, click Fill in the left pane, select Gradient fill in the right pane, and then do the following: In the Type list, select Linear. Click the button next to Direction, and then click Linear Diagonal (first row, third option from the left). In the Angle box, enter 135%. Under Gradient stops, click Add or Remove until two stops appear on the slider. Under Gradient stops, on the slider, customize the gradient stops as follows: Click on the left stop, and then do the following: In the Stop position box, enter 0%. Select Stop 2 from the list, and then do the following: Click the button next to Color, and then under Theme Colors click White, Background 1, Darker 15% (third row, first option from the left). In the Stop position box, enter 100%. Select the rectangle. Under Drawing Tools, on the Format tab, in the Size group, do the following: In the Shape Height box, enter 0.33”. In the Shape Width box, enter 10”. On the Home tab, in the Drawing group, click Shapes, and then under Basic Shapes, click Right Triangle (first row, fourth option from the left). On the Home tab, in the Drawing group, click the arrow next to Shape Outline, and then click No Outline. On the Home tab, in the Drawing group, click the arrow next to Shape Fill, and then under Theme Colors click White, Background 1, Darker 15% (third row, first option from the left). Select the triangle. Under Drawing Tools, on the Format tab, in the Size group, do the following: On the slide, drag to draw a triangle. In the Shape Height box, enter 1.33”. On the Home tab, in the Drawing group, click the arrow next to Shape Fill, and then click White, Background 1, Darker 15% (third row, first option from the left). On the Home tab, in the Drawing group, click Arrange, and then do the following: Position the rectangle and the triangle so that the bottom edge of the triangle and the top edge of the rectangle are touching. Press and hold SHIFT and select both the rectangle and the triangle. Point to Align, and then click Align Bottom. Point to Align, and then click Align Center. Under Group Objects, click Group. In the Format Shape dialog box, on the Size tab, under Size and rotate, in the Rotation box, enter 180°. Under Drawing Tools, on the Format tab, in the Arrange group, click the arrow next to Rotate, and then click More Rotation Options. On the Home tab, in the Clipboard group, click the arrow next to Copy, and then click Duplicate. On the Home tab, in the Drawing group, click Arrange, point to Align, and then do the following: Click Align Center. On the Home tab, in the Drawing group, click the arrow next to Shape Fill, and then under Theme Colors click White, Background 1 (first row, first option from the left). Click Align Top. To reproduce the original text and rectangle, do the following: On the Home tab, in the Clipboard group, click the arrow next to Copy, and then click Duplicate. Repeat this step until you have a total of five groups of shapes. Press and hold SHIFT and select the original text box and rectangle. On the Home tab, in the Drawing group, click Arrange, and then under Group Objects click Group. Also in the Selection and Visibility pane, press and hold CTRL and select all five groups of rectangles and text boxes. On the Home tab, in the Editing group, click Select, and then click Selection Pane. In the Selection and Visibility pane, select each of the groups and drag on the slide to form a series of steps. On the Home tab, in the Drawing group, click Arrange, point to Align, and then click Distribute Horizontally. On the Home tab, in the Drawing group, click Arrange, point to Align, and then click Distribute Vertically. To change the text on the duplicate rectangles, click in each text box and edit the text. ORDER BY Hassan Tariq – FAST NUCES Hassan Tariq
8
Simple SQL Query SELECT attributes
FROM relations (possibly multiple, joined) WHERE conditions (selections) Product PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi SELECT * FROM Product WHERE category=‘Gadgets’ PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 Hassan Tariq – FAST NUCES
9
Selections What goes in the WHERE clause:
x = y, x < y, x <= y, etc Pattern matching on strings: s LIKE p (next) Product(Name, Price, Category, Manufacturer) Find all products whose name mentions ‘gizmo’: SELECT * FROM Products WHERE PName LIKE ‘%gizmo%’ Hassan Tariq – TRG /FAST NUCES / LUMS
10
COMPARISON Product PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi SELECT PName, Price, Manufacturer FROM Product WHERE Price BETWEEN 19 and 30 PName Price Manufacturer Gizmo $19.99 GizmoWorks Powergizmo $29.99 Use of BETWEEN Hassan Tariq – TRG /FAST NUCES / LUMS
11
Eliminating Duplicates
Category Gadgets Photography Household SELECT DISTINCT category FROM Product Compare to: Category Gadgets Photography Household SELECT category FROM Product Hassan Tariq – FAST NUCES
12
SUM() / MIN() / MAX() / AVG() Function
Hassan Tariq 5/5/2018 AGGREGATE FUNCTIONS COUNT() Function SELECT COUNT(column_name) FROM table_name SUM() / MIN() / MAX() / AVG() Function SELECT SUM(column_name) FROM table_name SELECT MAX(column_name) FROM table_name SELECT MIN(column_name) FROM table_name IS NULL Function select * from STUDENT where name is null Hassan Tariq – TRG /FAST NUCES / LUMS Hassan Tariq
13
? Ordering the Results SELECT pname, price, manufacturer FROM Product
WHERE category=‘gizmo’ AND price > 50 ORDER BY price, Ordering is ascending, unless you specify the DESC keyword. SELECT Category FROM Product ORDER BY PName PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi ? Hassan Tariq – TRG /FAST NUCES / LUMS
14
GROUPING Product PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi SELECT Manufacturer, COUNT(*) as Total FROM Product GROUP BY Manufacturer Manufacturer Total GizmoWorks 2 Canon 1 Hitachi Use of GROUP BY Hassan Tariq – TRG /FAST NUCES / LUMS
15
GROUPING with Condition
Product PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi SELECT Manufacturer, COUNT(*) as Total FROM Product GROUP BY Manufacturer HAVING COUNT(*)>2 Manufacturer Total GizmoWorks 2 Use of GROUP BY with HAVING Hassan Tariq – TRG /FAST NUCES / LUMS
16
Multiple Tables: INNER JOIN LEFT OUTER JOIN RIGHT OUTER JOIN
SQL provides a convenient operation to retrieve information from multiple tables. The Join operation will combine the tables into one large table with all possible combinations, and then it will filter the rows of this combined table to yield useful information. INNER JOIN 1 LEFT OUTER JOIN 2 RIGHT OUTER JOIN 3 FULL OUTER JOIN 4 Hassan Tariq – DB CS-C
17
Join in SQL Connect two or more tables: What is the Connection between
PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Product Company CName StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 What is the Connection between them ?
18
INNER Join A INNER Join is a join operation that joins two tables by their common column. This operation is similar to the setting relation of two tables. Hassan Tariq – TRG /FAST NUCES / LUMS
19
INNER Join in SQL Find all products under $200 manufactured in Japan and return their names &prices. Product Company PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Cname StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 SELECT PName, Price FROM Product INNER JOIN Company ON Manufacturer=CName WHERE Country=‘Japan’ AND Price <= 200 PName Price SingleTouch $149.99 Hassan Tariq – TRG /FAST NUCES / LUMS
20
INNER Join in SQL What is the problem ? What’s the solution ?
Product Company PName Price Category Manufacturer Gizmo $19.99 Gadgets GizmoWorks Powergizmo $29.99 SingleTouch $149.99 Photography Canon MultiTouch $203.99 Household Hitachi Cname StockPrice Country GizmoWorks 25 USA Canon 65 Japan Hitachi 15 SELECT Country FROM Product INNER JOIN Company ON Manufacturer=CName WHERE Category=‘Gadgets’ What is the problem ? What’s the solution ? Country ??
21
Left Outer Join Left Outer Join returns all matched rows, plus all unmatched rows from the table on the left of the join clause (use nulls in fields of non-matching tuples) Hassan Tariq – TRG /FAST NUCES / LUMS
22
SELECT s.sid, s.name, r.bid FROM Sailors s LEFT OUTER JOIN Reserves r ON s.sid = r.sid
Hassan Tariq – TRG /FAST NUCES / LUMS
23
Right Outer Join Right Outer Join returns all matched rows, plus all unmatched rows from the table on the right of the join clause
24
SELECT r.sid, b.bid, b.name FROM Reserves r RIGHT OUTER JOIN Boats b ON r.bid = b.bid
25
Full Outer Join Full Outer Join returns all (matched or unmatched) rows from the tables on both sides of the join clause
26
SELECT r.sid, b.bid, b.name FROM Reserves r FULL OUTER JOIN Boats b ON r.bid = b.bid
Note: in this case it is the same as the ROJ because bid is a foreign key in reserves, so all reservations must have a corresponding tuple in boats.
27
Desirable Properties of Transactions
Atomicity. A transaction is an atomic unit of processing; it should either be performed in its entirety or not performed at all. Consistency preservation. A transaction should be consistency preserving, meaning that if it is completely executed from beginning to end without interference from other transactions, it should take the database from one consistent state to another. Isolation. A transaction should appear as though it is being executed in isolation from other transactions, even though many transactions are executing concurrently. That is, the execution of a transaction should not be interfered with by any other transactions executing concurrently. Durability or permanency. The changes applied to the database by a committed transaction must persist in the database. These changes must not be lost because of any failure. Hassan Tariq – TRG /FAST NUCES / LUMS
28
Constraints Constraints are the rules enforced on data columns on table. This ensures the accuracy and reliability of the data in the database. NOT NULL - Indicates that a column cannot store NULL value PRIMARY KEY - Ensures that a column (or combination of two or more columns) have an unique identity which helps to find a particular record in a table more easily and quickly FOREIGN KEY - Ensure the referential integrity of the data in one table to match values in another table DEFAULT - Specifies a default value when specified none for this column Hassan Tariq – TRG /FAST NUCES / LUMS
29
NORMALIZATION Normalization is a approach of decomposing tables to eliminate data redundancy Types of Normal Form First Normal Form Second Normal Form Third Normal Form Hassan Tariq – TRG /FAST NUCES / LUMS
30
FIRST NORMAL FORM Hassan Tariq – TRG /FAST NUCES / LUMS
31
Solution for first normal form
32
Second normal form
33
Solution to second normal form
34
Third normal form Hassan Tariq – TRG /FAST NUCES / LUMS
35
Third Normal Form - example
36
STORED Procedure? Stored Procedure In SQL server can be defined as the set of logically group of SQL statement which are grouped to perform a specific task. There are many benefits of using a stored procedure A stored procedure is nothing more than a prepared SQL code that you save so that you can reuse the code over and over again. Hassan Tariq – TRG /FAST NUCES / LUMS
37
Benefits of using Stored Procedures
Explanation Modular Programming You can write a stored procedure once, then call it from multiple places in your application hence reducing development time It can accept input parameters, return output values as parameters, or return success or failure status messages Performance Stored procedures provide faster code execution Reduced network traffic Security Users can execute a stored procedure without needing to execute any of the statements directly Users can specifically be granted permission to execute only Stored procedures instead of allowing them to execute queries on tables directly. Faster execution: Stored procedures are parsed and optimized as soon as they are created and the stored procedure is stored in memory. This means that it will execute a lot faster than sending many lines of SQL code from your application to the SQL Server. Doing that requires SQL Server to compile and optimze your SQL code every time it runs. Reduce Network Traffic: If you send many lines of SQL code over the network to your SQL Server, this will impact on network performance. This is especially true if you have hundreds of lines of SQL code and/or you have lots of activity on your application. Running the code on the SQL Server (as a stored procedure) eliminates the need to send this code over the network. The only network traffic will be the parameters supplied and the results of any query Security: Therefore, a stored procedure can provide advanced database functionality for users who wouldn't normally have access to these tasks, but this functionality is made available in a tightly controlled way. Hassan Tariq – TRG /FAST NUCES / LUMS
38
Stored Procedure vs. SQL Statement
Creating Check syntax Compile First Time - Check syntax Compile Execute Return data First Time Execute Return data Second Time - Check syntax Compile Execute Return data Second Time Execute Return data Hassan Tariq – TRG /FAST NUCES / LUMS
39
creating/executing Store Procedure
Creating Stored Procedure: CREATE PROCEDURE dbo.procedure_name AS BEGIN SELECT * FROM Employee WHERE name = ‘hassan’ END Executing Stored Procedure: EXECUTE dbo.procedure_name Type Explanation Stored Procedure (without parameters) The created procedure has no parameter and simply returns the result of query. Stored Procedure (with parameters) The real power of stored procedures is its ability to accept parameters and return results based upon those parameters.
40
Triggers A trigger is a special kind of stored procedure that automatically executes when an event occurs in the database server Unlike stored procedures, an SQL trigger cannot be directly called from an application. Instead, an SQL trigger is invoked by the database management system on the execution of a triggering insert, update, or delete operation Hassan Tariq – TRG /FAST NUCES / LUMS
41
DML trigger DML triggers is a special type of stored procedure that automatically takes effect when a data manipulation language (DML) event takes place that affects the table defined in the trigger. DML events include INSERT, UPDATE, or DELETE statements. Basically, DML triggers are classified into two main types: - (i) After Triggers (For Triggers) (ii) Instead Of Triggers Hassan Tariq – TRG /FAST NUCES / LUMS
42
DDL trigger They fire in response to a variety of Data Definition Language (DDL) events. These events primarily correspond to SQL statements that start with the keywords CREATE, ALTER, and DROP. Use DDL triggers when you want to do the following: You want to prevent certain changes to your database schema. You want to record changes or events in the database schema. Hassan Tariq – TRG /FAST NUCES / LUMS
43
views The SQL VIEW is a virtual table that does not physically exist. Rather, it is created by a SQL statement that joins one or more tables. Create View view_name AS SELECT * FROM Student Benefits Views can join and simplify multiple tables into a single virtual table Views take very little space to store; the database contains only the definition of a view, not a copy of all the data which it presents a view can limit the degree of exposure of the underlying tables to the outer world: a given user may have permission to query the view, while denied access to the rest of the base table Hassan Tariq – TRG /FAST NUCES / LUMS
44
Indexes An index can be created in a table to find data more quickly and efficiently. An index can be used to efficiently find all row matching some column in your query and then walk through only that subset of the table to find exact matches. If you don't have indexes on any column in the WHERE clause, the SQL server have to walk through the whole table and check every row to see if it matches, which may be a slow operation on big tables. Benefits Searching For Records Sorting Records Grouping Records
45
INDEXES
46
index Clustered index Non-Clustered index
A clustered index stores the actual data rows at the leaf level of the index. It determines the physical order of data in a table. There can be only one clustered index per table clustered indexes are efficient for finding rows Non-Clustered index The lowest rows of a nonclustered index contain the nonclustered index key values and each key value entry has pointers to the data rows containing the key value. The data rows are not stored in order based on the nonclustered key. Hassan Tariq – TRG /FAST NUCES / LUMS
47
Frequent Database interview questions
Difference between Unique and Primary Key? How to retrieve data from two tables sharing many to many relations? What is difference between DELETE, DROP and TRUNCATE commands? What is the difference between a HAVING CLAUSE and a WHERE CLAUSE? Difference between StoreProcedure and View? What is Self-Join? What are cursors ? Hassan Tariq – TRG /FAST NUCES / LUMS
48
That’s all Folks Best of luck In case of issue, contact me at
Hassan Tariq – TRG /FAST NUCES / LUMS
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.