Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Views, Triggers, Functions, Stored Procedures, Indexing and Joins


Published on

Published in: Education, Technology
  • Be the first to comment

Views, Triggers, Functions, Stored Procedures, Indexing and Joins

  1. 1. Disclaimer: This presentation is prepared by trainees ofbaabtra as a part of mentoring program. This is not officialdocument of baabtra –Mentoring PartnerBaabtra-Mentoring Partner is the mentoring division of baabte System Technologies Pvt .Ltd
  2. 2. Views, Triggers, Functions- Calling a function, return type,Stored Procedures, Indexing and Joins
  3. 3. VIEWS• The view is a virtual table. It does not physically exist. Rather, it is created by aquery joining one or more tables.• A view contains rows and columns, just like a real table• The fields in a view are fields from one or more real tables in the databaseCreating an SQL VIEWSyntax:CREATE VIEW view_name ASSELECT column_name(s)FROM table_nameWHERE condition;
  4. 4. View Creation - Example• View Creation - ExampleCREATE VIEW sup_ordersAS SELECT suppliers.supplier_id, orders.quantity, orders.priceFROM suppliers, ordersWHERE suppliers.supplier_id = orders.supplier_id and suppliers.supplier_name = IBM;• This View (Create statement) would create a virtual table based on the result set of the selectstatement. You can now query the view as followsSELECT * FROM sup_orders;
  5. 5. Updating VIEW• You can modify the definition of a VIEW without dropping it by using the followingsyntaxCREATE OR REPLACE VIEW view_nameAS SELECT columnsFROM tableWHERE predicates;• View Modify - ExampleCREATE or REPLACE VIEW sup_ordersAS SELECT suppliers.supplier_id, orders.quantity, orders.priceFROM suppliers, ordersWHERE suppliers.supplier_id = orders.supplier_idand suppliers.supplier_name = Microsoft;
  6. 6. Dropping VIEW• The syntax for dropping a VIEW :DROP VIEW view_name;• View Drop - ExampleDROP VIEW sup_orders;Question: Can you update the data in an view?Answer : A view is created by joining one or more tables. When you update record(s) in a view, itupdates the records in the underlying tables that make up the View.So, yes, you can update the data in View providing you have the proper privileges to theunderlying tables.Question: Does the SQL View exist if the table is dropped from the database?Answer: Yes, View continues to exist even after one of the tables (that the SQL View is based on) isdropped from the database. However, if you try to query the View after the table has beendropped, you will receive a message indicating that the View has errors.
  7. 7. TRIGGER• What is a Trigger?A trigger is a block structure which is fired when a DML statements like Insert,Delete, Update is executed on a database table. A trigger is triggered automaticallywhen an associated DML statement is executed.• Syntax of TriggersCREATE [OR REPLACE ] TRIGGER trigger_name{BEFORE | AFTER | INSTEAD OF }{INSERT [OR] | UPDATE [OR] | DELETE}[OF col_name]ON table_name[REFERENCING OLD AS o NEW AS n][FOR EACH ROW]WHEN (condition) ;
  8. 8. TRIGGER• The syntax for a dropping a Trigger is:DROP TRIGGER trigger_name ON tbl_name;• The syntax for a disabling a Trigger is:ALTER TRIGGER trigger_name DISABLE;• The syntax for a enabling a Trigger is:ALTER TRIGGER trigger_name ENABLE;
  9. 9. Example• Creating TriggerCREATE TRIGGER deleted_detailssBEFOREDELETE on tbl_customerFOR EACH ROWEXECUTE PROCEDURE customerss_delete();• Drop Triggerdrop trigger delete_details on tbl_customer;
  10. 10. Functions• A function is a group of statements that executes upon request• Python provides many built-in functions and allows programmers to define their ownfunctions• A request to execute a function is known as a function call• When a function is called, it may be passed arguments that specify data upon whichthe function performs its computation• Functions defined within class statements are also called methodsThe def Statement• The def statement is the most common way to define a functionSyntaxdef function-name(parameters):statement(s)
  11. 11. FunctionsThe return keyword• A function is created to do a specific task• Often there is a result from such a task• The return keyword is used to return values from a function• A function may or may not return a value• If a function does not have a return keyword, it will send a None value
  12. 12. Exampledef showMessage(msg):print msgdef cube(x):return x * x * xdef main():x = cube(3)print xshowMessage("Computation finished.")print showMessage("Ready.")main()output:baabtra@baabtra-desktop:~$ python ppt.py27Computation finished.Ready.None
  13. 13. Calling Functions• A function call is an expression with the following syntax:function-object(arguments)• function-object It is most often the functions name.• The parentheses denote the function-call operation itself.• Arguments, in the simplest case, is a series of zero or more expressions separated bycommas (,), giving values for the functions corresponding formal parameters
  14. 14. Calling Functionstotal = 0;# Function definition is heredef sum( arg1, arg2 ):# Add both the parameters and return them."total = arg1 + arg2;# Here total is local variable.print "Inside the function local total : ", totalreturn total;def main():# Now you can call sum functionsum( 10, 20 );print "Outside the function global total : ", totalmain()output:baabtra@baabtra-desktop:~$ python ppt2.pyInside the function local total : 30Outside the function global total : 0
  15. 15. AdvantageThe advantages of using functions are:• Reducing duplication of code• Improving clarity of the code• Reuse of code• Information hiding
  16. 16. INDEX• The CREATE INDEX statement is used to create indexes in tables• Indexes allow the database application to find data fast; without reading the wholetable• An index can be created in a table to find data more quickly and efficiently• The users cannot see the indexes, they are just used to speed up searches/queries
  17. 17. INDEX• CREATE INDEX SyntaxCreates an index on a table. Duplicate values are allowed:CREATE INDEX index_nameON table_name (column_name);• CREATE UNIQUE INDEX SyntaxCreates a unique index on a table. Duplicate values are not allowed:CREATE UNIQUE INDEX index_nameON table_name (column_name);• UNIQUE indicates that the combination of values in the indexed columns must beunique
  18. 18. INDEX• Rename an IndexThe syntax for renaming an index is:ALTER INDEX index_name RENAME TO new_index_name;• Drop an IndexThe syntax for dropping an index is:DROP INDEX index_name;
  19. 19. JOINS• Joins are used to query data from two or more tables, based on a relationshipbetween certain columns in these tables• Types of JoinsLEFT JOIN: Return all rows from the left table, even if there are no matches in theright tableRIGHT JOIN: Return all rows from the right table, even if there are no matches inthe left tableFULL JOIN: Return rows when there is a match in one of the tables
  20. 20. INNER JOIN• The INNER JOIN keyword returns rows when there is at least one match in bothtables• INNER JOIN SyntaxSELECT column_name(s)FROM table_name1INNER JOIN table_name2ON table_name1.column_name=table_name2.column_name;• If there are rows in “table_name1 " that do not have matches in " table_name2 ",those rows will NOT be listed
  21. 21. LEFT JOIN• The LEFT JOIN keyword returns all rows from the left table (table_name1), even ifther are no matches in the right table (table_name2)• LEFT JOIN SyntaxSELECT column_name(s)FROM table_name1LEFT JOIN table_name2ON table_name1.column_name=table_name2.column_name;
  22. 22. RIGHT JOIN• The RIGHT JOIN keyword returns all the rows from the right table (table_name2),even if there are no matches in the left table (table_name1)• RIGHT JOIN SyntaxSELECT column_name(s)FROM table_name1RIGHT JOIN table_name2ON table_name1.column_name=table_name2.column_name;
  23. 23. FULL JOIN• The FULL JOIN keyword return rows when there is a match in one of the tablesFULL JOIN SyntaxSELECT column_name(s)FROM table_name1FULL JOIN table_name2ON table_name1.column_name=table_name2.column_name;• The FULL JOIN keyword returns all the rows from the left table (Table1), and all the rowsfrom the right table (Table2). If there are rows in " Table1 " that do not have matches in "Table2", or if there are rows in " Table2" that do not have matches in " Table1 ", those rowswill be listed as well.
  24. 24. stored procedure• In a database management system (DBMS), a stored procedure is a set of Structured QueryLanguage (SQL) statements with an assigned name thats stored in the database in compiledform so that it can be shared by a number of programs.• preserving data integrity (information is entered in a consistent manner)Data integrity means the correctness and consistency of dataEnforcing data integrity ensures the quality of the data in the databaseConsider following two examples of data integriry in a database1) If an employee is entered with an employee_id value of 123, the database should not allowanother employee to have an ID with the same value2) If you have an employee_rating column intended to have values ranging from 1 to 5, thedatabase should not accept a value of 6
  25. 25. ExampleCREATE OR REPLACE FUNCTION insert_tbl_customer(int,text,date,text,int,boolean)RETURNS void AS$delimiter$INSERT INTO tbl_customer (pk_int_cu_id, vchr_cname, dat_dob, vchr_email,bint_phone,bln_sex)VALUES ($1,$2,$3,$4,$5,$6);$delimiter$LANGUAGE SQL;select insert_tbl_customer(201,john,1990-10-5,b@gmail,94,true);
  26. 26. If this presentation helped you, please visit our and like it.Thanks in | |
  27. 27. Contact Us