SQL With Joins
SQL With Joins
(SQL)
SQL
SQL is an acronym of Structured Query Language.It is a
standard language developed and used for accessing and
modifying relational databases.
The SQL language was originally developed at the IBM research
laboratory in San José, in connection with a project developing
a prototype for a relational database management system
called System R in the early 70s.
SQL is being used by many database management systems.
Some of them are:
MySQL
PostgreSQL
Oracle
SQLite
Microsoft SQL Server
Advantages of using SQL SQL
Interactive Language-This language can be used for
communicating with the databases and receive answers to the
complex questions in seconds.
Multiple data views-The users can make different views of
database structure and databases for the different users.
Portability-SQL can be used in the program in PCs, servers,
laptops, and even some of the mobile phones and even on
different dbms softwares
No coding needed-It is very easy to manage the database
systems without any need to write the substantial amount of
code by using the standard SQL.
Well defined standards-Long established are used by the SQL
databases that is being used by ISO and ANSI. There are no
standards adhered by the non-SQL databases.
SQL
Char, Varchar, Date and Time values should be enclosed with single (‘ ‘) or double(
“”) quotes inMySQL. varchar is used in MySQL and varchar2 is used in Oracle.
SQL
Database Commands in MySql
Getting listings of available databases
mysql> SHOW DATABASES;
Creating a database-
mysql> CREATE database myschool;
Deleting a database mysql> DROP database <databasename>;
to remove table mysql> drop table <tablename>;
After database creation we can open the database using
USE command mysql> USE myschool;
To show list of tables in opened database
mysql> SHOW TABLES;
Creating a table in the database is achieved with CREATE table statement.
mysql> CREATE TABLE student (lastname varchar(15),
firstname varchar(15), city varchar(20), class char(2));
The command DESCRIBE is used to view the structure of a table.
mysql> DESCRIBE student;
SQL
Database Commands in MySql
To insert new rows into an existing table use the INSERT command:
mysql>INSERT INTO student values(‘dwivedi’,’freya’,’Udaipur’,’4’);
We can insert record with specific column only
mysql>INSERT INTO student(lastname,firstname,city) values(‘dwivedi’,’Mohak’,’Udaipur’,);
With the SELECT command we can retrieve previously inserted rows:
A general form of SELECT is:
SELECT what to select(field name) FROM table(s)
WHERE condition that the data must satisfy;
• Comparison operators are: < ; <= ; = ; != or <> ; >= ; >
• Logical operators are: AND ; OR ; NOT
•Comparison operator for special value NULL: IS
mysql> SELECT * FROM student;
SQL
Database Commands in MySql
Selecting rows by using the WHERE clause in the SELECT command
mysql> SELECT * FROM student WHERE class=“4";
Selecting specific columns(Projection) by listing their names
mysql> SELECT first_name, class FROM student;
Selecting rows with null values in specific column
mysql> SELECT * FROM Student WHERE City IS NULL ;
BETWEEN- to access data in specified range mysql>
SELECT * FROM Student WHERE class between 4 and 6;
IN- operator allows us to easily test if the expression in the list of values.
mysql> SELECT * FROM Student WHERE class in (4,5,6);
SQL
Database Commands in MySql
Pattern Matching – LIKE Operator
A string pattern can be used in SQL using the following wild card
% Represents a substring in any length
_ Represents a single character
Example:
‘A%’ represents any string starting with ‘A’ character.
‘_ _A’ represents any 3 character string ending with ‘A’.
‘_B%’ represents any string having second character ‘B’
‘_ _ _’ represents any 3 letter string.
A pattern is case sensitive and can be used with LIKE operator.
mysql> SELECT * FROM Student WHERE Name LIKE ‘A%’;
mysql> SELECT * FROM Student WHERE Name LIKE ’%Singh%’;
mysql> SELECT Name, City FROM Student WHERE Class>=8 AND Name LIKE
‘%Kumar%’ ;
SQL
Now we write the query – select * from student order by class desc;
Now we write query–select * from student order by class asc, marks asc;
Query result will be ascending order of class and if same class exists
then ordering will done on marks column(ascending order)
SQL
MySQL Order by– e.g.
Suppose we are having student table with following data.
Now we write query–select * from student order by class asc, marks desc;
Query result will be ascending order of class and if same class exists
then ordering will done on marks column(descending order)
SQL
An aggregate function performs a calculation on multiple values
and returns a single value. For example, you can use the AVG()
aggregate function that takes multiple numbers and returns the
average value of the numbers.Following is the list of aggregate
functions supported by mysql.
Name Purpose
SUM() Returns the sum of given column.
MIN() Returns the minimum value in the given column.
MAX() Returns the maximum value in the given column.
AVG() Returns the Average value of the given column.
COUNT() Returns the total number of values/ records as per given
column.
SQL
Aggregate Functions & NULL
Consider a table Emp having following records as-
Null values are excluded while (avg)aggregate function is used
Emp
Code Name Sal
E1 Mohak NULL
E2 Anuj 4500
E3 Vijay NULL
E4 Vishal 3500
SQL Queries E5 Anil 4000
Result of query
mysql> Select Sum(Sal) from EMP; 12000
mysql> Select Min(Sal) from EMP; 3500
mysql> Select Max(Sal) from EMP; 4500
mysql> Select Count(Sal) from EMP; 3
mysql> Select Avg(Sal) from EMP; 4000
mysql> Select Count(*) from EMP; 5
SQL
Query result will be unique occurrences of class values along with counting of
students(records) of each class(sub group).
SQL
Query result will be unique occurrences of class values along with average
marks of each class(sub group).
SQL
MySQL GROUP BY with aggregate functions (with where and order by clause)
we are having student table with following data.
Query result will be unique occurrences of class values where class<10 along with
average marks of each class(sub group) and descending ofer of marks.
SQL
Query result will be unique occurrences of class values along with average
marks of each class(sub group) and each class having average marks<90.
SQL
MySQL GROUP BY with aggregate functions & having clause
we are having student table with following data.
Query result will be unique occurrences of class values along with average
marks of each class(sub group) and each class having less than 3 rows.
SQL
Types of JOIN
Following are the types of JOIN that we can use in SQL:
• Inner
• Outer
• Left
• Right
Natural JOIN(⋈)
Natural Join is a type of Inner join which is based on
column having same name and same datatype present
in both the tables to be joined.E.g.
Select * from a natural join b;
SQL
LEFT Outer Join
The left outer join returns a resultset table with the matched data from the
two tables and then the remaining rows of the left table and null from the
right table's columns. E.g.
Mysql query –
Select * from a left outer join b on
(a.name=b.name);
Mysql query –
Select * from a left outer join b on
(a.name=b.name) union Select * from
a right outer join b on
(a.name=b.name) ;
EMPLOYEE TABLE
EmpID EmpFname EmpLname Age EmailID PhoneNo Address
1 Vardhan Kumar 22 [email protected] 9876543210 Delhi
2 Himani Sharma 32 [email protected] 9977554422 Mumbai
3 Aayushi Shreshth 24 [email protected] 9977555121 Kolkata
4 Hemanth Sharma 25 [email protected] 9876545666 Bengaluru
5 Swatee Kapoor 26 [email protected] 9544567777 Hyderabad
PROJECT TABLE
This type of join returns those records which have matching values in both
tables. So, if you perform an INNER join operation between the Employee table
and the Projects table, all the tuples which have matching values in both the
tables will be given as output.
Syntax:
SELECT Table1.Column1,Table1.Column2,Table2.Column1,....
FROM Table1 INNER JOIN Table2 ON
Table1.MatchingColumnName = Table2.MatchingColumnName;
SLECT Employee.EmpID, Employee.EmpFname,
Example: 1
Employee.EmpLname, Projects.ProjectID, Projects.ProjectName
2
FROM Employee
3
INNER JOIN Projects ON Employee.EmpID=Projects.EmpID;
Output:
EmpID EmpFname EmpLname ProjectID ProjectName
Syntax:
SELECT Table1.Column1,Table1.Column2,Table2.Column1,....
FROM Table1 LEFT JOIN Table2 ON
Table1.MatchingColumnName = Table2.MatchingColumnName;
Example:
Full Join or the Full Outer Join returns all those records which
either have a match in the left(Table1) or the right(Table2)
table.
Syntax:
SELECT
Table1.Column1,Table1.Column2,Table2.Column1
,.... FROM Table1 FULL JOIN Table2 ON
Table1.MatchingColumnName =
Table2.MatchingColumnName;
Example:
1SELECT Employee.EmpFname, Employee.EmpLname, Projects.ProjectID
2FROM Employee
3FULL JOIN Projects EmpFname EmpLname ProjectID
4ON Employee.EmpID = Projects.EmpID; Vardhan Kumar 111
Himani Sharma 222
Aayushi Shreshth 333
Output: Aayushi Shreshth 444
Hemanth Sharma NULL
Swatee Kapoor 555
NULL NULL 666
NULL NULL 777
NULL NULL 888