Unit 2 SQL Basics and Joins
Unit 2 SQL Basics and Joins
Introduction to SQL
3.1 Introduction
SQL fully abbreviated as Structured Query Language can be defined as a domain-
specific language used to manage the relational databases and performs different operations
on the data stored in them. SQL is used as their standard database language by all the
relational database management systems like Oracle, Informix, Posgres, SQL server, MySQL,
MS Access, and Sybase.
3.1. 1 Characteristics of SQL
SQL is easy to learn.
SQL is used to access data from relational database management systems.
SQL can execute queries against the database.
SQL is used to describe the data.
SQL is used to define the data in the database and manipulate it when needed.
SQL is used to create and drop the database and table.
SQL is used to create a view, stored procedure, function in a database.
SQL allows users to set permissions on tables, procedures, and views.
database structure.
1. Binary Data types: There are Three types of binary Datatypes which are given below
Data Type Description
Binary It has a maximum length of 8000 bytes. It contains fixed-length binary data.
varbinary It has a maximum length of 8000 bytes. It contains variable-length binary data.
Image It has a maximum length of 2,147,483,647 bytes.
Data
Description
type
It has a maximum length of 8000 characters. It contains Fixed-length non-unicode
char
characters.
5. Date and time Data type: The subtypes are given below:
2
What is MySQL: MySQL is a fast, easy to use relational database. It is currently the most
popular open-source database. It is very commonly used in conjunction with PHP scripts to
create powerful and dynamic server-side applications.
MySQL is used for many small and big businesses. It is developed, marketed and supported by
MySQL AB, a Swedish company. It is written in C and C++.
MySQL is very friendly with PHP, the most popular language for web development.
MySQL supports large databases, up to 50 million rows or more in a table. The default file size
limit for a table is 4GB, but you can increase this (if your operating system can handle it) to a
theoretical limit of 8 million terabytes (TB).
perform specific tasks, functions, and queries of data. SQL can perform various tasks like
create a table, add data to tables, drop the table, modify the table, set permission for users.
7
Structured Query Language(SQL) as we all know is the database language by the use of which
we can perform certain operations on the existing database and also we can use this language
to create a database. SQL uses certain commands like Create, Drop, Insert etc. to carry out the
required tasks. These SQL commands are mainly categorized into four categories as discussed
below:
3.6.1 DDL (Data Definition Language) : DDL or Data Definition Language actually consists of
the SQL commands that can be used to define the database schema. It simply deals with
descriptions of the database schema and is used to create and modify the structure of
1. CREATE – is used to create the database or its objects (like table, index, function, views,
store procedure and triggers).
Syntax:
CREATE TABLE TABLE_NAME (COLUMN_NAME DATATYPES[,....]);
Example:
CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB DATE);
3. TRUNCATE–is used to remove all records from a table, including all spaces allocated for
the records are removed, it does not disturb the structure of table, i.e after truncate your table
with all attributes will be exist but all the rows in table will be deleted.
Syntax:
TRUNCATE TABLE table_name;
Example:
TRUNCATE TABLE EMPLOYEE;
8
4. COMMENT –is used to add comments to the data dictionary. This is similar to comment
we add in program block.
/* add comment here*/
5. RENAME –is used to rename an objects like database, tables, views etc. existing in the
database.
Syntax: Rename Object old_name to new_name;
Example: Rename table emp to employee;
6. ALTER-is used to alter the structure of the table, It is used to alter the structure of the
table. This change could be either to modify the characteristics of an existing attribute or
probably to add a new attribute or to remove the existing attributes.
Syntax:
ALTER TABLE command to add a New Column in an existing table is as
2. INSERT – is Data Manipulation Language command used to insert data into a table. It can
insert a single record at a time in a table.
Syntax:
INSERT INTO TABLE_NAME (col1, col2, …... col N) VALUES (value1, value2, ….. valueN);
3. UPDATE – is Data Manipulation Language command used to update existing data within a
table. It can modify the any values or attributes for the particular tuple or row based on
specified condition.
Syntax:
UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [WHERE
CONDITION]
For example:
UPDATE students SET User_Name = 'Sonoo' WHERE Student_Id = '3'
3.6.3 DCL (Data Control Language) : DCL includes commands such as GRANT and REVOKE
which mainly deals with the rights, permissions and other controls of the database system.
1. GRANT-gives user’s access privileges to database. It is also used to create a database user
with some privileges.
Example
GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;
10
DELETE FROM CUSTOMERS WHERE AGE = 25;
COMMIT;
2. ROLLBACK– rollbacks a transaction in case of any error occurs. Rollback command is used
to undo transactions that have not already been saved to the database. It can rollback all
transaction which are not yet committed.
Syntax:
ROLLBACK;
Example:
DELETE FROM CUSTOMERS WHERE AGE = 25;
ROLLBACK;
3. SAVEPOINT–sets a savepoint within a transaction.
1 StephanDelhi 1 Stephan 97 19
2 Kathrin Noida 2 Kathrin 86 21
3 David Ghaziabad 3 David 74 18
4 Alina Gurugram 4 Alina 90 20
5 John 96 18
1. Creating view: A view can be created using the CREATE VIEW statement. We can create
Syntax:
CREATE VIEW view_name AS SELECT column1, column2.....FROM table_name WHERE condit
ion;
2. Creating View from a single table: In this example, we create a View named DetailsView
from the table Student_Detail.
CREATE VIEW DetailsView AS SELECT NAME, ADDRESS FROM Student_Details WHERE
STU_ID < 4;
Just like table query, we can query the view to view the data: SELECT * FROM DetailsView;
11
Output: NAME ADDRESS
Stephan Delhi
Kathrin Noida
David Ghaziabad
2. Creating View from multiple tables: View from multiple tables can be created by simply
Example, a view is created named MarksView from two tables Student_Detail and
Student_Marks.
CREATE VIEW MarksView AS SELECT Student_Detail.NAME, Student_Detail.ADDRESS, Studen
t_Marks.MARKS FROM Student_Detail, Student_Mark WHERE Student_Detail.NAME = Student
_Marks.NAME;
To display data of View MarksView: SELECT * FROM MarksView;
SQL> SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY
> 4500) ;
13
4. Subqueries with the UPDATE Statement: The subquery can be used in conjunction with
the UPDATE statement. Either single or multiple columns in a table can be updated when
using a subquery with the UPDATE statement. The basic syntax is as follows.
UPDATE table SET column_name = new_value [ WHERE OPERATOR [ VALUE ] (SELECT
COLUMN_NAME FROM TABLE_NAME [ WHERE) ] )
Example: Assuming, we have CUSTOMERS_BKP table available which is backup of
CUSTOMERS table. The following example updates SALARY by 0.25 times in the CUSTOMERS
table for all the customers whose AGE is greater than or equal to 27.
SQL> UPDATE CUSTOMERS SET SALARY = SALARY * 0.25 WHERE AGE IN (SELECT AGE
FROM CUSTOMERS_BKP WHERE AGE >= 27 );
This would impact two rows and finally CUSTOMERS table would have the following records.
the DELETE statement like with any other statements mentioned above. The basic syntax is as
follows.
3.10.1 MySQL WHERE Clause: MySQL WHERE Clause is used with SELECT, INSERT, UPDATE
and DELETE clause to filter the results. It specifies a specific position where you have to do
the operation.
Syntax: WHERE conditions;
Conditions: It specifies the conditions that must be fulfilled for records to be selected.
17
SELECT * FROM officers WHERE address = 'Mau';
MySQL WHERE Clause with AND condition: In this example, we are retrieving data from the
table "officers" with AND condition.
SELECT * FROM officers WHERE address = 'Lucknow' AND officer_id < 5;
3.10.2 ORDER BY: The ORDER BY clause sorts the result-set in ascending or descending
order. It sorts the records in ascending order by default. DESC keyword is used to sort the
records in descending order.
Syntax: ELECT column1, column2 FROM table_name WHERE condition ORDER BY column1,
column2... ASC|DESC;
Where ASC: It is used to sort the result set in ascending order by expression. DESC: It sorts
the result set in descending order by expression.
Example: Sorting Results in Ascending Order
SELECT * FROM CUSTOMER ORDER BY NAME;
3.10.3 GROUP BY Clause: The MYSQL GROUP BY Clause is used to collect data from multiple
records and group the result by one or more column. It is generally used in a SELECT
statement. You can also use some aggregate functions like COUNT, SUM, MIN, MAX, AVG etc.
on the grouped column.
Syntax: SELECT expression1, expression2,... expression_n, aggregate_function (expression)
FROM tables [WHERE conditions] GROUP BY expression1, expression2, ... expression_n;
Parameters: expression1, expression2, ... expression_n: It specifies the expressions that
are not encapsulated within an aggregate function and must be included in the GROUP BY
clause.
Aggregate function: It specifies a function such as SUM, COUNT, MIN, MAX, or AVG etc.
tables: It specifies the tables, from where you want to retrieve the records. There must be at
least one table listed in the FROM clause.
WHERE conditions: It is optional. It specifies the conditions that must be fulfilled for the
records to be selected.
SQL GROUP BY statement is used to arrange identical data into groups. The GROUP BY
statement is used with the SQL SELECT statement.
The GROUP BY statement follows the WHERE clause in a SELECT statement and precedes
the ORDER BY clause.
The GROUP BY statement is used with aggregation function.
Syntax: ELECT column FROM table_name WHERE conditions GROUP BY column ORDER BY
column
3.10.4 MySQL HAVING Clause: MySQL HAVING Clause is used with GROUP BY clause. It
always returns the rows where condition is TRUE.
Syntax:
18
SELECT expression1, expression2, ... expression_n, aggregate_function (expression) FROM ta
bles [WHERE conditions] GROUP BY expression1, expression2, ... expression_n HAVING cond
ition;
Parameters
Aggregate function: It specifies any one of the aggregate function such as SUM, COUNT, MIN,
MAX, or AVG.
expression1, expression2, ... expression_n: It specifies the expressions that are not
encapsulated within an aggregate function and must be included in the GROUP BY clause.
WHERE conditions: It is optional. It specifies the conditions for the records to be selected.
HAVING condition: It is used to restrict the groups of returned rows. It shows only those
groups in result set whose conditions are TRUE.
Execute the following query:
SELECT emp_name, SUM(working_hours) AS "Total working hours" FROM employees GROU
3.10. 5: MySQL Distinct Clause: MySQL DISTINCT clause is used to remove duplicate records
from the table and fetch only the unique records. The DISTINCT clause is only used with the
SELECT statement.
Syntax:
SELECT DISTINCT expressions FROM tables [WHERE conditions];
Parameters
expressions: specify the columns or calculations that you want to retrieve.
tables: specify the name of the tables from where you retrieve records. There must be at least
one table listed in the FROM clause.
WHERE conditions: It is optional. It specifies the conditions that must be met for the records
to be selected.
Note:
If you put only one expression in the DISTINCT clause, the query will return the unique
values for that expression.
If you put more than one expression in the DISTINCT clause, the query will retrieve unique
combinations for the expressions listed.
In MySQL, the DISTINCT clause doesn't ignore NULL values. So if you are using the
DISTINCT clause in your SQL statement, your result set will include NULL as a distinct
value.
Use the following query: SELECT DISTINCT address FROM officers;
19
operation is used to combine the two or more SQL SELECT statements. Four different types of SET
operations, are
1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS The Second table,
ID NAME
1 Abhi
2 Adam
2 Adam
3 Chester
3.11.3 INTERSECT: Intersect operation is used to combine two SELECT statements, but it
only returns the records which are common from both SELECT statements. In case of
Intersect the number of columns and datatype must be same. But remember MySQL does
not support INTERSECT operator.
Select * from First INTERSECT Select * from Second
20
3.11.4 MINUS: The Minus operation combines results of two SELECT statements and return only
those in the final result, which belongs to the first set of the result.
Select * from First MINUS Select * from Second
The result set table will look like
ID NAME
2 adam
3.12 SET MEMBERSHIP: To Check whether any
values is a member of some set or not set membership is used. In SQL set membership is used
with IN and NOT IN operator which allows you to easily test if an expression matches any
value in a list of values. The IN operator checks a value within a set of values separated by
commas and retrieve the rows from the table which are matching. The IN returns 1 when the
search value present within the range otherwise returns 0. Consider Example with Relations
SavingAccount(Laccno, SCust_Name, Balance)
Loan Account (Laccno, LCust_Name, Balance)
1. Find list of all customer name which are having Loan account as well saving account
Select * from SavingAccount where SCust_Name IN (Select * from LoanAccount)
2. Find list of Customer Belonging to any ne of following city.
SELECT * FROM Customers WHERE Country IN ('Germany', 'France', 'UK');
3.13 SET COMPARISON: Set comparison is SQL is used to compare the values in two set.
Using arithmetic comparison operator we can just compare two values but if we want to
compare more than one elements of two sets then set comparison can be used with SOME and
ALL operator.
First we will understand how All and Some operatorwork. Remember SOME operator will
match any element of Set A with SOME elements of Set B. and ALL Operator will match any
element of Set A with ALL elements of Set B. Consider two Sets
X={100, 200, 300} And Y = {300, 400, 500}
Condition for Some Result for Some Condition for All Result for All
Operator Operator Operator Operator
A<SOMEB TRUE A<ALLB TRUE
A <= SOME B TRUE A<=ALLB TRUE
A >= SOME B TRUE A>=ALLB FALSE
A>SOMEB FALSE A>ALLB FALSE
A <> SOME B TRUE A<>ALLB FALSE
A=SOMEB TRUE A=ALLB FALSE
Consider the example with following relations
located in nashik.
21
Select bname from branch where assets > SOME (Select assets from Branch where
bcity=’Nashik’)
2. Find the name of all branches that have assets greater than those of ALL branches
located in nashik.
Select bname from branch where assets > ALL (Select assets from Branch where
bcity=’Nashik’)
2. LEFT JOIN
3. RIGHT JOIN
4. FULL JOIN
Table 1: Customer
order_id order_
Table 2: Order
date amount customer_id
1 07/04/1776 $234.56 1
2 03/14/1760 $78.50 3
3 05/23/1784 $124.00 2
22
4 09/03/1790 $65.50 3
5 07/21/1795 $25.50 10
6 11/27/1787 $14.40 9
1. INNER JOIN: The INNER JOIN keyword selects all rows from both the tables as long as the
condition satisfies. This keyword will create the result-set by combining all rows from both the
tables where the condition satisfies i.e value of the common field will be same. Syntax: Select
t2.matching_Column
t1.matching_Column= t2.matching_Column
name
George Washington 07/04/1776 $234.56
John Adams 05/23/1784 $124.00
Thomas Jefferson 03/14/1760 $78.50
Thomas Jefferson 09/03/1790 $65.50
James Madison NULL NULL
James Monroe NULL NULL
3. RIGHT JOIN: it is also called as Right Outer Join. RIGHT JOIN is similar to LEFT JOIN. This
join returns all the rows of the table on the right side of the join and matching rows for the
table on the left side of join. The rows for which there is no matching row on left side, the
result-set will contain null. RIGHT JOIN is also known as RIGHT OUTER JOIN.
Syntax: Select t1.attribute, t2.attribute from Table1 t1 RIGHT JOIN Table t2 ON
t1.matching_Column= t2.matching_Column
t1.matching_Column= t2.matching_Column
24
1. COUNT Function: COUNT function is used to Count the number of rows in a database
table. It can work on both numeric and non-numeric data types. It uses the COUNT(*) that
returns the count of all the rows in a specified table. COUNT(*) considers duplicate and
Null.