Unit5 Joins SubQ Views Tran
Unit5 Joins SubQ Views Tran
Overview
What are Joins? Types of Joins
Cross join Inner join Left join Right Join
Basic SQL
Overview
What are subqueries? Types of subqueries
Normal Correlated
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
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
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
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
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
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
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
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
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
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
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
Basic SQL
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
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
Basic SQL
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
Basic SQL
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
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
Basic SQL
Basic SQL
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
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
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)
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
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);
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
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
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
FROM
Basic SQL
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
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
Basic SQL
QUESTION TIME
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
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.
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.
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
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.
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
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
Basic SQL
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;
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;
Basic SQL
TRANSACTIONS
Basic SQL
TRANSACTIONS
Syntax:
BEGIN TRANSACTION Insert into table1.. SAVEPOINT firststep Update table2.. IF ERR = 1 ROLLBACK firststep COMMIT;
Basic SQL
Question Time
Please try to limit the questions to the topics discussed during the session. Thank you .
Basic SQL