Unit 3
Interactive SQL and Performance
Tuning
Data Types in SQL:-
• Char(length) :A FIXED length string (can contain letters, numbers, and
special characters). The size parameter specifies the column length in
characters - can be from 0 to 255. Default is 1
• Varchar(length):A VARIABLE length string (can contain letters, numbers,
and special characters). The size parameter specifies the maximum column
length in characters - can be from 0 to 65535
• Boolean:Equal to CHAR(), but stores binary byte strings.
The size parameter specifies the column length in bytes. Default is 1
• Smallint:A small integer. Signed range is from -32768 to 32767. Unsigned
range is from 0 to 65535. The size parameter specifies the maximum display
width (which is 255)
• Integer or int:A medium integer. Signed range is from -2147483648 to
2147483647. Unsigned range is from 0 to 4294967295. The size parameter
specifies the maximum display width (which is 255)
• Decimal or Dec:An exact fixed-point number. The total number of digits is
specified in size. The number of digits after the decimal point is specified in
the d parameter. The maximum number for size is 65. The maximum
number for d is 30. The default value for size is 10. The default value for d is
0.
• Float(p):A floating point number. MySQL uses the p value to determine
whether to use FLOAT or DOUBLE for the resulting data type. If p is from
0 to 24, the data type becomes FLOAT(). If p is from 25 to 53, the data type
becomes DOUBLE()
• Date:A date. Format: YYYY-MM-DD. The supported range is from '1000-
01-01' to '9999-12-31‘
• Time:A time. Format: hh:mm:ss. The supported range is from '-838:59:59'
to '838:59:59'
DDL: Data Definition Language
1) Create:- to create new table or database
Syntax:-CREATE TABLE TABLE_NAME (COLUMN_NAME
DATATYPES(SIZE);
Eg. :-CREATE TABLE Student (Reg_no varchar2(10), Name char(30), DOB
date,Address varchar2(50));
2) Alter:- To add a new column in the table or modify an existing column in the
table
Syntax:-ALTER TABLE table_name ADD column_name COLUMN-definition;
ALTER TABLE MODIFY(COLUMN DEFINITION....);
Eg. :-Alter table Student add (subject varchar(10));
3) Truncate:-delete data from table
Syntax:-TRUNCATE TABLE table_name;
Eg. :-TRUNCATE table students;
4) Drop:- to drop a table
Syntax:-DROP TABLE <table_name>
Eg. :-Drop table student;
5) Rename:- to rename a table
Syntax:-RENAME TABLE <OldTableName> TO <NewTableName>
Eg. :- RENAME table Student TO Stu
DML: Data Manipulation Language
• DML commands are used for manipulating the data stored in the table
and not the table itself.
1) Insert- to insert a new row
Syntax- INSERT INTO TABLE_NAME VALUES (value1, value2, value3, ....
valueN);
Example- INSERT INTO students VALUES ('60', 'Tom', Erichsen');
2) Update-to update existing row
Syntax - UPDATE table_name SET [column_name1=
value1,...column_nameN = valueN] [WHERE CONDITION]
Example-UPDATE students SET FirstName = 'Jhon', LastName= 'Wick'
WHERE StudID = 3;
3) Delete- to delete a row
Syntax-DELETE FROM table_name [WHERE condition];
Example-DELETE FROM students WHERE FirstName = 'Jhon';
4) Select-retrieve records from one or more table
Syntax-SELECT expressions FROM TABLES WHERE conditions;
Example-SELECT FirstName FROM Student WHERE RollNo > 15;
TCL: Transaction Control Language
• DML commands are not auto-committed. It means changes are not
permanent to database, they can be rolled back.
• These commands can revert back changes made by other commands by
rolling the data back to its original state. It can also make any temporary
change permanent.
1) Commit- to permanently save
Syntax- Commit;
2) Rollback- to undo change
Syntax- ROLLBACK;
3) savepoint - to save temporarily
Syntax- SAVEPOINT SAVEPOINT_NAME;
Example- SAVEPOINT RollNo;
DCL: Data Control Language
• Data control language are the commands to grant and take back authority
from any database user.
1) Grant- grant permission of right
Syntax- GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER,
ANOTHER_USER;
Example- GRANT SELECT ON Users TO'Tom'@'localhost;
2) Revoke- take back permission.
Syntax- REVOKE privilege_nameON object_nameFROM {user_name
|PUBLIC |role_name}
Example- REVOKE SELECT, UPDATE ON student FROM BCA, MCA;
SQL GROUP BY statement
This statement is used to group records having the same values. The GROUP BY
statement is often used with the aggregate functions to group the results by one or
more columns. Apart from this, the GROUP BY clause is also used with the
HAVING clause and JOINS to group the result set based on conditions.
SQL GROUP BY Syntax
SELECT Column 1, Column 2,..., Column N
FROM Table Name
WHERE Condition
GROUP BY Column Name(s)
ORDER BY Column Name(s);
Here, you can add the aggregate functions before the column names, and also a
HAVING clause at the end of the statement to mention a condition.
Examples:
EmpID EmpName EmpEmail PhoneNumber Salary City
1 Nidhi nidhi@sample.com 9955669999 50000 Mumbai
2 Anay anay@sample.com 9875679861 55000 Pune
3 Rahul rahul@sample.com 9876543212 35000 Delhi
4 Sonia sonia@sample.com 9876543234 35000 Delhi
5 Akash akash@sample.com 9866865686 25000 Mumbai
Use SQL GROUP BY on single column
Example:
Write a query to retrieve the number of employees in each city.
SELECT COUNT(EmpID), City FROM Employees GROUP BY City;
Output:
You will see the following output:
Count(EmpID) City
2 Delhi
2 Mumbai
1 Pune
Use SQL GROUP BY on multiple columns
Example:
Write a query to retrieve the number of employees having different salaries in each
city.
SELECT City, Salary, Count(*) FROM Employees GROUP BY City, Salary;
Output:
The table will have the following data:
City Salary Count(*)
Delhi 35000 2
Mumbai 25000 1
Mumbai 50000 1
Pune 55000 1
Use SQL GROUP BY with ORDER BY
When we use the SQL GROUP BY statement with the ORDER BY clause, the
values get sorted either in ascending or descending order.
Example:
Write a query to retrieve the number of employees in each city, sorted in
descending order.
SELECT COUNT(EmpID), City FROM Employees GROUP BY City
ORDER BY COUNT(EmpID) DESC;
Output:
The table will have the following data:
Count(EmpID) City
2 Delhi
2 Mumbai
1 Pune
Use SQL GROUP BY with HAVING clause
The SQL GROUP BY statement is used with ‘HAVING’ clause to mention
conditions on groups. Also, since we cannot use the aggregate functions with the
WHERE clause, we have to use the ‘HAVING’ clause to use the aggregate
functions with GROUP BY.
Example: Write a query to retrieve the number of employees in each city, having
salary > 15000
SELECT COUNT(EmpID), City FROM Employees GROUP BY City
HAVING SALARY > 15000;
Output:
Since all are records in the Employee table have a salary > 15000, we will see the
following table as output:
Count(EmpID) City
2 Delhi
2 Mumbai
1 Pune
SQL JOIN
A JOIN clause is used to combine rows from two or more tables, based on a related
column between them.
SQL INNER JOIN Keyword
The INNER JOIN keyword selects records that have matching values in both
tables.
INNER JOIN Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
SQL INNER JOIN Example
SELECT emp.eid,emp.did,dept.dname
FROM emp
INNER JOIN dept ON emp.did= dept.did;
The INNER JOIN keyword selects all rows from both tables as long as there is a
match between the columns. If there are records in the "emp" table that do not have
matches in "dept", these records will not be shown
Emp dept
empid ename did did dname
1 Mahesh 100
50 Dev
2 Suhas 200 100 HR
3 Jayendra 100 200 TIS
Output:-
empid did dname
1 100 HR
2 200 TIS
3 100 HR
SQL LEFT (Outer) JOIN
LEFT (OUTER) JOIN: Returns all records from the left table, and the matched
records from the right table.The result is 0 records from the right side, if there is no
match.
LEFT JOIN Syntax
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;
In some databases LEFT JOIN is called LEFT OUTER JOIN.
SQL LEFT JOIN Example
SELECT emp.eid,emp.did,dept.dname
FROM emp
LEFT JOIN dept ON emp.did = dept.did
The LEFT JOIN keyword returns all records from the left table (emp), even if there
are no matches in the right table (dept).
Output:-
empid did dname
1 100 HR
2 200 TIS
3 500 Null
SQL RIGHT JOIN Keyword
The RIGHT JOIN keyword returns all records from the right table (table2), and the
matching records from the left table (table1). The result is 0 records from the left
side, if there is no match.
RIGHT JOIN Syntax
SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;
In some databases RIGHT JOIN is called RIGHT OUTER JOIN.
SQL RIGHT JOIN Example
SELECT emp.eid,emp.did,dept.dname
FROM emp
RIGHT JOIN dept ON emp.did = dept.did
The RIGHT JOIN keyword returns all records from the right table (emp), even if
there are no matches in the left table (dept).
Output:-
empid did dname
1 100 HR
2 200 TIS
Null 50 DEV
SQL FULL OUTER JOIN Keyword
The FULL OUTER JOIN keyword returns all records when there is a match in left
(table1) or right (table2) table records.
FULL OUTER JOIN and FULL JOIN are the same.
FULL OUTER JOIN Syntax
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name
WHERE condition;
FULL OUTER JOIN can potentially return very large result-sets!
SQL FULL OUTER JOIN Example
SELECT emp.eid,emp.did,dept.dname
FROM emp
FULL JOIN dept ON emp.did = dept.did
The FULL OUTER JOIN keyword returns all matching records from both tables
whether the other table matches or not. So, if there are rows in "Dept" that do not
have matches in "emp", or if there are rows in "emp" that do not have matches in
"dept", those rows will be listed as well.
Output:-
empid did dname
1 100 HR
2 200 TIS
3 500 NULL
NULL 50 DEV
SQL Self Join
A self join is a regular join, but the table is joined with itself.
Self Join Syntax
SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;
T1 and T2 are different table aliases for the same table.
SQL Self Join Example
SELECT e.ename[employee],m.ename[manager]
FROM emp e
INNER JOIN emp m on e.mid=m.eid
employe manager
Mahesh Ganesh
Ganesh Sanjay
Sanjay Sanjay
Sub Queries
• The Subquery or Inner query is an SQL query placed inside another SQL
query. It is embedded in the HAVING or WHERE clause of the SQL
statements.
SELECT * FROM Student_Details
WHERE Stu_Marks> ( SELECT AVG(Stu_Marks ) FROM Student_Details);
Student_RollNo. Stu_Name Stu_Marks Stu_City
1001 Akhil 85 Agra
1002 Balram 78 Delhi
1003 Bheem 87 Gurgaon
1004 Chetan 95 Noida
1005 Diksha 99 Agra
1006 Raman 90 Ghaziabad
1007 Sheetal 68 Delhi
O/P
Student_RollNo. Stu_Name Stu_Marks Stu_City
1003 Bheem 87 Gurgaon
1004 Chetan 95 Noida
1005 Diksha 99 Agra
1006 Raman 90 Ghaziabad
SQL Operators
Arithmetic Operators
These operators are used to perform operations such as addition, multiplication,
subtraction etc.
Operator Operation Description
+ Addition Add values on either side of the operator
Used to subtract the right hand side value from
– Subtraction
the left hand side value
Multiples the values present on each side of the
* Multiplication
operator
Divides the left hand side value by the right hand
/ Division
side value
Divides the left hand side value by the right hand
% Modulus
side value; and returns the remainder
Comparison Operators
These operators are used to perform operations such as equal to, greater than, less
than etc.
Operator Operation Description
Used to check if the values of both operands are
= Equal to equal or not. If they are equal, then it returns
TRUE.
Returns TRUE if the value of left operand is
> Greater than
greater than the right operand.
Checks whether the value of left operand is less
< Less than
than the right operand, if yes returns TRUE.
Used to check if the left operand is greater than
Greater than or
>= or equal to the right operand, and returns TRUE,
equal to
if the condition is true.
Less than or Returns TRUE if the left operand is less than or
<=
equal to equal to the right operand.
Used to check if values of operands are equal or
<> or != Not equal to
not. If they are not equal then, it returns TRUE.
Not greater Checks whether the left operand is not greater
!>
than than the right operand, if yes then returns TRUE.
SET Operations in SQL
SQL supports few Set operations which can be performed on the table data.
These are used to get meaningful results from data stored in the table, under
different special conditions.
UNION is used to combine the results of two or more SELECT statements.
However it will eliminate duplicate rows from its resultset. In case of union,
number of columns and datatype must be same in both the tables, on which
UNION operation is being applied.
UNION ALL
This operation is similar to Union. But it also shows the duplicate rows.
INTERSECT
Intersect operation is used to combine two SELECT statements, but it only
retuns the records which are common from both SELECT statements. In case
of Intersect the number of columns and datatype must be same.
NOTE: MySQL does not support INTERSECT operator.
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.
The SQL LIKE Operator
The LIKE operator is used in a WHERE clause to search for a specified pattern in
a column.There are two wildcards often used in conjunction with the LIKE
operator:
% The percent sign represents zero, one, or multiple characters
_ The underscore represents a single character
SQL LIKE Examples
1.The following SQL statement selects all customers with a CustomerName
starting with "a":
SELECT * FROM Customers
WHERE CustomerName LIKE 'a%';
2. The following SQL statement selects all customers with a CustomerName
ending with "a":
SELECT * FROM Customers
WHERE CustomerName LIKE '%a';
3. The following SQL statement selects all customers with a CustomerName that
have "or" in any position:
SELECT * FROM Customers
WHERE CustomerName LIKE '%or%';
4.The following SQL statement selects all customers with a CustomerName that
have "r" in the second position:
SELECT * FROM Customers
WHERE CustomerName LIKE '_r%';
5. The following SQL statement selects all customers with a CustomerName that
starts with "a" and are at least 3 characters in length:
SELECT * FROM Customers
WHERE CustomerName LIKE 'a__%';
6. The following SQL statement selects all customers with a ContactName that
starts with "a" and ends with "o":
SELECT * FROM Customers
WHERE ContactName LIKE 'a%o';
7. The following SQL statement selects all customers with a CustomerName that
does NOT start with "a":
SELECT * FROM Customers
WHERE CustomerName NOT LIKE 'a%';
Inbuilt Functions
String Functions:
LOWER : This function converts alpha character values to lowercase.
Ex. SELECT LOWER('DATABASE@456') FROM DUAL;
Output: database@456
UPPER : This function converts alpha character values to uppercase.
Ex. SELECT UPPER('pune') FROM DUAL;
Output: PUNE
INITCAP : This function converts alpha character values to uppercase for the first
letter of each word and all others in lowercase.
Ex. SELECT INITCAP(' computer science ') FROM DUAL;
Output: Computer Science
LENGTH : This function returns the length of the input string.
Ex. SELECT LENGTH('Learning Is Fun') FROM DUAL;
Output:15
SUBSTR : This function returns a portion of a string from a given start point to an
end point. If a substring length is not given, then SUBSTR returns all the
characters till the end of string (from the starting position specified).
Ex. SELECT SUBSTR('Database Management System', 9, 7) FROM DUAL;
Output: Manage
LPAD and RPAD : These functions return the strings padded to the left or right (
as per the use ) ;
Ex. SELECT LPAD('100',5,'*') FROM DUAL;
Output: **100
SELECT RPAD('5000',7,'*') FROM DUAL;
Output: 5000***
TRIM : This function trims the string input from the start or end (or both) If no
string or char is specified to be trimmed from the string and there exists some extra
space at start or end of the string, then those extra spaces are trimmed off.
Ex. SELECT TRIM('G' FROM 'Gujarat') FROM DUAL;
Output: ujarat
SELECT TRIM(' Gujarat ') FROM DUAL;
Output: Gujarat
REPLACE : This function searches for a character string and, if found, replaces it
with a given replacement string at all the occurrences of the string.
Ex. SELECT REPLACE('DATA MANAGEMENT', 'DATA','DATABASE')
FROM DUAL;
Output: DATABASE MANAGEMENT