0% found this document useful (0 votes)
104 views49 pages

Unit5 Joins SubQ Views Tran

Unit 5: Joins, Sub Queries, Views and transactions. JOIN is a query that combines data from more than one table by means of a single statement.

Uploaded by

arjunnarang18
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
104 views49 pages

Unit5 Joins SubQ Views Tran

Unit 5: Joins, Sub Queries, Views and transactions. JOIN is a query that combines data from more than one table by means of a single statement.

Uploaded by

arjunnarang18
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

Unit 5: Joins, Sub Queries Views and Transactions

Pratian Technologies (India) Pvt. Ltd.


www.pratian.com

Overview
What are Joins? Types of Joins
Cross join Inner join Left join Right Join

Unions SQL Functions


String Date Numeric Summarized

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Overview
What are subqueries? Types of subqueries
Normal Correlated

Predicates with subqueries Restrictions with subqueries Views Transactions


What are transactions Transaction control Commit Rollback
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

JOINS
JOIN is a query that combines data from more than one table by means of a single statement Joining is done in SQL by specifying the tables to be joined in the FROM clause Most join queries contain WHERE conditions that compare two columns, each from a different table. Such a condition is called join condition

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

CROSS JOIN
A cross-join between two tables takes the data from each row in table1 and joins it to the data from each row in table2. Example information
mysql

To

select

students

with

their

course

> SELECT s.Name, c.Course -> FROM Students s, Courses c

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

CROSS JOIN
Students Table
StudentId 1001 1002 Name Krishna S Raghav V Age 18 19 CourseId 1 2

Courses Table
CourseId 1 2 Name Krishna S Krishna S Raghav V Raghav V
Copyright 2010 Pratian Technologies www.pratian.com

Course Basic SQL Excel Course Basic SQL Excel Basic SQL Excel
Basic SQL

EQUI JOIN
An equi join is a join condition containing an equality operator Is also called inner join or simple join In the equi-join the comparison we are making between two columns is that they match the same value. We can use this method to select certain fields from both tables and only the correct rows will be joined together. Example To select students with their course information
SELECT s.StudentId, s.Name, c.CourseId, c.Course FROM Students s, Courses c WHERE s.CourseId = c.CourseId

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

EQUI JOIN
Students Table
StudentId 1001 1002 Name Krishna S Raghav V Age 18 19 CourseId 1 2

Courses Table
CourseId 1 2 Course Basic SQL Excel

Result
Name Krishna S Raghav V
Copyright 2010 Pratian Technologies www.pratian.com

Course Basic SQL Excel


Basic SQL

SELF JOIN
A self join is a join of a table to itself The table appears twice in the FROM clause and is followed by table aliases, that qualify table names in the join condition The table rows are combined and the rows which satisfy the condition are returned To get names of all students with referred by student names
SELECT s.Name as StudentName, s.Age, r.Name as ReferredBy FROM Students s, Students r WHERE s.ReferredById = r.StudentId

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

SELF JOIN
Students
StudentId 1001 1002 Name Krishna S Raghav V Age 18 19 CourseId 1 2 ReferredById NULL 1001

Result
Student Name Age Raghav V 19 ReferredBy Krishna

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

LEFT JOIN
A left join extends the result of a simple join Returns all rows that satisfy the join conditions and those rows from left table for which no rows from the other satisfy the join condition Example: To get all students information, even those without course information
SELECT s.Name, s.Age, c.CourseId, c.Course FROM Students s LEFT JOIN Courses c ON s.CourseId = c.CourseId

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

LEFT JOIN
Students
StudentId 1001 1002 1003 Name Krishna S Raghav V Veena N Age 18 19 18 Course Basic SQL Excel CourseId 1 NULL 2

Courses
CourseId 1 2

Result
Name Krishna S Raghav V Veena N
Copyright 2010 Pratian Technologies www.pratian.com

Age 18 19 18

CourseId 1 NULL 2
Basic SQL

Course Basic SQL NULL Excel

RIGHT JOIN
A right join extends the result of a simple join Returns all rows that satisfy the join conditions and those rows from right table for which no rows from the other satisfy the join condition Example: To get all courses with their students, even those courses which doesnt have students assigned
SELECT s.Name, s.Age, c.CourseId, c.Course FROM Students s RIGHT JOIN Courses c ON s.CourseId = c.CourseId

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

RIGHT JOIN
Students
StudentId 1001 1002 1003 Name Krishna S Raghav V Veena N Age 18 19 18 Course Basic SQL Excel CourseId 1 NULL 1

Courses
CourseId 1 2

Result
Name Krishna S Veena N NULL
Copyright 2010 Pratian Technologies www.pratian.com

Age 18 18 NULL

CourseId 1 1 2
Basic SQL

Course Basic SQL Basic SQL Excel

UNION
UNION is used to combine the result from multiple SELECT statements into a single result set There are few conditions to be kept in mind, when we use UNION
The number of columns in each SELECT statement has to be the same The data type of the columns in the column list of the SELECT statement must be the same or at least convertible.

Syntax:
SELECT statement UNION [DISTINCT | ALL] SELECT statement UNION [DISTINCT | ALL ]
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

UNION
By default the UNION removes all duplicated rows from the result set even if you dont explicit use DISTINCT after the UNION keyword If you use UNION ALL explicitly, the duplicated rows will remain in the result set For Ex:
SELECT StudentId as Id, Name as Desc, Fees FROM Students WHERE Name LIKE %K UNION SELECT StudentId as Id, Name as Desc, Fees FROM Students WHERE Name LIKE %A
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

SQL FUNCTIONS
Apart from aggregate functions there are some single row functions which can be used in queries They can be classified into the below mentioned categories
String Numeric Date Summarized

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

SQL FUNCTIONS - String


UPPER (string)
Converts all characters of a given string to upper case SELECT UPPER(Name), JoinDate, Fees FROM Students

LOWER(string)
Converts all characters of a given string to lower case SELECT LOWER(Name), JoinDate, Fees FROM Students

REVERSE(string)
Returns the reverse of a string Select REVERSE(ABCD) Output - DCBA
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

SQL FUNCTIONS - String


SUBSTRING(string, pos, len) or SUBSTRING(string FROM pos FOR len)
Extracts substring from a given string considering the position and length provided Select SUBSTRING(Krishna, 2, 5) Output rishn

CONCAT(string1, string2,.)
Returns a string after concatenating all the strings provided Arguments passed cannot be null Select CONCAT(My, S, Q, L) Output - MySQL

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

SQL FUNCTIONS - String


LTRIM(string)
Returns string with leading space characters removed SELECT LTRIM( Krishna)

RTRIM(string)
Similar to LTRIM. Removes trailing space characters

CHAR_LENGTH(string)
Returns the length of the string
Note: This is only a partial list

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

SQL FUNCTIONS - Numeric


ROUND(x, d) or ROUND(x)
Rounds the argument x to d decimal places Select ROUND(150.225, 2) Output 150.22

ABS(x)
Returns the absolute values Select ABS(-32) Output = 32

SQRT(x)
Returns the square root a non-negative number Select SQRT(4) Output = 2
Note: This is only a partial list.
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

SQL FUNCTIONS - Date


DATE(expr)
Returns the date from a given date and time value Select DATE(2010-12-31 08:30:00) Output 2010-12-31

CURDATE()
Returns the current date Select CURDATE() Output 2010-11-01

DAY(date)
Returns day of the month, in the range 1 31 SELECT DAY(2010-11-01) Output - 1

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

SQL FUNCTIONS - Date


DATE_ADD(date, INTERVAL expr unit)
Function performs date arithmetic SELECT '2008-12-31 23:59:59' + INTERVAL 1 SECONDS; Output - 2009-01-01 00:00:00 There are many unit values that can be specified SECONDS MINUTES HOURS DAYS WEEKS MONTHS YEARS etc..
Note: This is only a partial list
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

SQL FUNCTIONS - Summarized


COUNT
Produces the number of rows query has selected

AVG
Produces the average of all selected values of a given column

MAX
Produces the largest of all selected values of a given column

MIN
Produces the smallest of all selected values of a given column

SUM
Produces the arithmetic sum of all selected values of a given column

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

SQL FUNCTIONS
http://dev.mysql.com/doc/refman/5.0/en/stringfunctions.html http://dev.mysql.com/doc/refman/5.0/en/numericfunctions.html http://dev.mysql.com/doc/refman/5.0/en/date-and-timefunctions.html

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

SUBQUERIES
A subquery is a SELECT statement within another statement Main advantages of subqueries are
Queries can be structured, so that it is possible to isolate each part of a statement Provide alternate ways to perform operations that would otherwise require complex joins or unions

Ex:
SELECT * FROM Table1 WHERE Column1 = (SELECT Column1 FROM Table2)

A subquery can return a scalar (a single value), a single row, a single column, or a table (one or more rows of one or more columns)

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

SUBQUERIES
Used in either SELECT, WHERE or FROM clauses of an SQL statement In the WHERE clause subqueries can become a part of the following predicates
Comparison predicate IN predicate ANY or ALL predicate EXISTS predicate

Subqueries cannot have ORDER BY clause

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

NORMAL SUBQUERIES
Does not need data from the outer query Subquery is evaluated only once Subquery generates values that are tested in the predicate of the outer query To list all students who have enrolled for Basic SQL course
SELECT Name, JoinDate FROM Students WHERE CourseId = (SELECT CourseId FROM Courses WHERE Course = BASIC SQL);

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

NORMAL SUBQUERIES
Students
StudentId 1001 1002 1003 Name Krishna S Raghav V Veena N Age 18 19 18 Course Basic SQL Excel CourseId 1 2 1

Courses
CourseId 1 2

Results
Name Krishna S Veena N Age 18 18 CourseId 1 2 Course Basic SQL Basic SQL

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

CORRELATED SUBQUERY
A correlated subquery uses any data from the FROM clause of the outer query The subquery is evaluated for each row of the outer query The subquery has to result in one value of the same data type as the left-hand side To get list of students and the number of courses they have joined
SELECT s.Name, s.Age, (Select count(*) FROM StudentCourses sc WHERE sc.StudentId = s.StudentId) as NoOfCourses FROM Students s

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

CORRELATED SUBQUERIES
Students
StudentId 1001 1002 Name Krishna S Raghav V Age 18 19 CourseId 1 2

StudentCourses
StudentId 1001 1001 1002 CourseId 1 2 1

Results
Name Krishna S Raghav V
Copyright 2010 Pratian Technologies www.pratian.com

Age 18 19
Basic SQL

NoOfCourses 1 2

PREDICATES WITH SUBQUERIES


Predicates that can be used with subqueries are
IN EXISTS ALL ANY/SOME IN SELECT DISTINCT(StudentId), Name, Fees FROM Students WHERE StudentId IN (Select st.StudentId StudentCourses st)

FROM

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

PREDICATES WITH SUBQUERIES


ALL
SELECT Name, Fees FROM Students WHERE Fees > ALL (SELECT Fees FROM Students WHERE CourseId = 1);

ANY
SELECT Name, Fees FROM Students WHERE Fess > ANY (SELECT Fees FROM Students WHERE CourseId = 1);

EXISTS
SELECT s.Name, s.Fees FROM Students s WHERE EXISTS (SELECT st.StudentId FROM StudentCourses st WHERE st.StudentId = s.StudentId);
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

SUBQUERIES
Can also be used in the FROM clause SELECT FROM (subquery) [AS] name
The [AS] name clause is mandatory as every table in FROM clause should have a name

Ex: Students who have paid more than Rs 1000 fees


SELECT StudentId, Name, Fees FROM (Select StudentId, Name, Fees From Students Where Fess >= 1000) as StudentsFeesGreater

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

SUBQUERIES - Restrictions
A subquery's outer statement can be any one of: SELECT, INSERT, UPDATE, DELETE, SET, or DO. In general, you cannot modify a table and select from the same table in a subquery. For example, this limitation applies to statements of the following forms
DELETE FROM t WHERE ... (SELECT ... FROM t ...); UPDATE t ... WHERE col = (SELECT ... FROM t ...); {INSERT|REPLACE} INTO t (SELECT ... FROM t ...); There are few more restrictions, but above mentioned are the most important

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

QUESTION TIME

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

VIEWS
Views are essentially saved SELECT queries that can themselves be queried It is stored as an object in the database They are used to provide easier access to normalized data Once you define a view then you can reference it like any other table in a database

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

VIEWS
Views have the following benefits: Security Views can be made accessible to users while the underlying tables are not directly accessible. This allows the DBA to give users only the data they need, while protecting other data in the same table.

Simplicity Views can be used to hide and reuse complex queries.

Column Name Simplification or Clarification Views can be used to provide aliases on column names to make them more memorable and/or meaningful.

Stepping Stone Views can provide a tiered approach in a "multi-level" query systematically.

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

VIEWS
Syntax
CREATE VIEW [view_name] AS SELECT statement goes here..

For Ex:
CREATE VIEW StudentCourses AS SELECT s.StudentId, s.Name, s.Fees, c.CourseId, c.Course FROM Students s, StudentCourses sc, Courses c WHERE s.StudentId = sc.StudentId and sc.CourseId = c.CourseId

To query view
SELECT * FROM StudentCourses

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

VIEWS
Some restrictions imposed on views are given below :
The view name must follow the rules for identifiers The view name must not be the same as that of the base table A view can be created if there is a SELECT permission on its base table. A SELECT INTO statement cannot be used in view declaration statement. A trigger or an index cannot be defined on a view. The CREATE VIEW statement cannot be combined with other SQL statements in a single batch.

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

VIEWS
ALTER VIEW
ALTER VIEW [view_name] AS SELECT statement that has been entered

For Ex:
ALTER VIEW StudentCourses AS SELECT s.StudentId, s.Name, s.Fees, c.Course FROM Students s, StudentCourses sc, Courses c WHERE s.StudentId = sc.StudentId and sc.CourseId = c.CourseId

DROP VIEW
DROP VIEW [view_name] DROP VIEW StudentCourses
Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

TRANSACTIONS
A transaction is a unit of work that may contain of one or more SQL statements A transaction is called atomic as the database modifications brought about by the SQL statements that constitute a transaction can be
Either made permanent to the database Or, undone from the database

The changes made to a table using INSERT, UPDATE or DELETE statements are not permanent till a transaction is marked complete

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

TRANSACTIONS
A transaction will never be complete unless each individual operation within the group is successful If any operation within the transaction fails, the entire transaction will fail During a session, a transaction begins when the first SQL command (DDL or DML) is encountered and ends when one of the following occurs
A DDL is encountered COMMIT/ROLLBACK statement is encountered Logging off from the session System failure

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

TRANSACTIONS Properties [ACID]


Atomicity: ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure, and previous operations are rolled back to their former state. Consistency: ensures that the database properly changes states upon a successfully committed transaction. Isolation: enables transactions to operate independently of and transparent to each other. Durability: ensures that the result or effect of a committed transaction persists in case of a system failure.

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

TRANSACTIONS - COMMIT
Committing a transaction makes permanent the changes resulting from all successful SQL statements in a transaction Syntax: COMMIT; AUTOCOMMIT option is available to execute COMMIT automatically whenever an INSERT, UPDATE or DELETE statement is executed Syntax: SET AUTOCOMMIT = 1;

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

TRANSACTIONS - ROLLBACK
Changes made to the database without COMMIT may be abandoned using the ROLLBACK statement When a transaction is rolled back, it is as if the transaction never occurred Syntax: ROLLBACK;

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

TRANSACTIONS

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

TRANSACTIONS
Syntax:
BEGIN TRANSACTION Insert into table1.. SAVEPOINT firststep Update table2.. IF ERR = 1 ROLLBACK firststep COMMIT;

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

Question Time
Please try to limit the questions to the topics discussed during the session. Thank you .

Copyright 2010 Pratian Technologies www.pratian.com

Basic SQL

You might also like