UNIT2
UNIT2
What is SQL?
SQL stands for Structured Query Language
o SQL is used to define the data in the database and manipulate it when needed.
The following table describes the differences between the SQL and NoSQL, which are
necessary to understand:
SQL No-SQL
2. The query language used in this database 2. The query language used in the No-SQL
system is a structured query language. database systems is a non-declarative query
language.
4. These databases are vertically scalable. 4. These databases are horizontally scalable.
5. The database type of SQL is in the form of 5. The database type of No-SQL is in the form of
tables, i.e., in the form of rows and columns. documents, key-value, and graphs.
7. Complex queries are easily managed in the 7. NoSQL databases cannot handle complex
SQL database. queries.
8. This database is not the best choice for 8. While No-SQL database is a perfect option for
storing hierarchical data. storing hierarchical data.
9. All SQL databases require object-relational 9. Many No-SQL databases do not require object-
mapping. relational mapping.
10. Gauges, CircleCI, Hootsuite, etc., are the 10. Airbnb, Uber, and Kickstarter are the top
top enterprises that are using this query enterprises that are using this query language.
language.
11. SQLite, Ms-SQL, Oracle, PostgreSQL, and 11. Redis, MongoDB, Hbase, BigTable, CouchDB,
MySQL are examples of SQL database and Cassandra are examples of NoSQL database
systems. systems.
Advantages of SQL
SQL provides various advantages which make it more popular in the field of data
science. It is a perfect query language which allows data professionals and users to
communicate with the database. Following are the best advantages or benefits of
Structured Query Language:
1. No programming needed
SQL does not require a large number of coding lines for managing the database
systems. We can easily access and maintain the database by using simple SQL
syntactical rules. These simple rules make the SQL user-friendly.
A large amount of data is accessed quickly and efficiently from the database by using
SQL queries. Insertion, deletion, and updation operations on data are also performed in
less time.
3. Standardized Language
SQL follows the long-established standards of ISO and ANSI, which offer a uniform
platform across the globe to all its users.
4. Portability
The structured query language can be easily used in desktop computers, laptops,
tablets, and even smartphones. It can also be used with other applications according to
the user's requirements.
5. Interactive language
We can easily learn and understand the SQL language. We can also use this language
for communicating with the database because it is a simple query language. This
language is also used for receiving the answers to complex queries in a few seconds.
The SQL language also helps in making the multiple views of the database structure for
the different database users.
Disadvantages of SQL
With the advantages of SQL, it also has some disadvantages, which are as follows:
1. Cost
The operation cost of some SQL versions is high. That's why some programmers cannot
use the Structured Query Language.
2. Interface is Complex
Another big disadvantage is that the interface of Structured query language is difficult,
which makes it difficult for SQL users to use and manage it.
The business rules are hidden. So, the data professionals and users who are using this
query language cannot have full database control.
An SQL developer must decide what type of data that will be stored inside each
column when creating a table. The data type is a guideline for SQL to
understand what type of data is expected inside of each column, and it also
identifies how SQL will interact with the stored data.
CHAR(size) 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(size) A VARIABLE length string (can contain letters, numbers, and special characters).
The size parameter specifies the maximum string length in characters - can be
from 0 to 65535
BINARY(size) Equal to CHAR(), but stores binary byte strings. The size parameter specifies the
column length in bytes. Default is 1
VARBINARY(size) Equal to VARCHAR(), but stores binary byte strings. The size parameter specifies
the maximum column length in bytes.
TINYBLOB For BLOBs (Binary Large Objects). Max length: 255 bytes
BLOB(size) For BLOBs (Binary Large Objects). Holds up to 65,535 bytes of data
MEDIUMBLOB For BLOBs (Binary Large Objects). Holds up to 16,777,215 bytes of data
BIT(size) A bit-value type. The number of bits per value is specified in size. The size parameter
can hold a value from 1 to 64. The default value for size is 1.
TINYINT(size) A very small integer. Signed range is from -128 to 127. Unsigned range is from 0 to 255.
The size parameter specifies the maximum display width (which is 255)
SMALLINT(size) 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)
MEDIUMINT(size) A medium integer. Signed range is from -8388608 to 8388607. Unsigned range is from 0
to 16777215. The size parameter specifies the maximum display width (which is 255)
INT(size) 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)
FLOAT(size, d) A floating 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. This syntax is deprecated
in MySQL 8.0.17, and it will be removed in future MySQL versions
Note: All the numeric data types may have an extra option: UNSIGNED or
ZEROFILL. If you add the UNSIGNED option, MySQL disallows negative values
for the column. If you add the ZEROFILL option, MySQL automatically also adds
the UNSIGNED attribute to the column.
Types of Operator
SQL operators are categorized in the following categories:
Following are the various arithmetic operators performed on the SQL data:
This example consists of an Employee_details table, which has four columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_Monthlybonus.
o Suppose, we want to add 20,000 to the salary of each employee specified in the table.
Then, we have to write the following query in the SQL:
o Suppose, we want to add the Salary and monthly bonus columns of the above table,
then we have to write the following query in SQL:
This example consists of an Employee_details table, which has four columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_Monthlybonus.
o Suppose we want to subtract 5,000 from the salary of each employee given in
the Employee_details table. Then, we have to write the following query in the SQL:
o If we want to subtract the penalty from the salary of each employee, then we have to
write the following query in SQL:
This example consists of an Employee_details table, which has four columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_Monthlybonus.
Emp Id Emp Name Emp Salary Penalty
Let's understand the below example which explains how to execute Division
Operator in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id,
Emp_Name, and Emp_Salary.
o Suppose, we want to half the salary of each employee given in the Employee_details
table. For this operation, we have to write the following query in the SQL:
This example consists of a Division table, which has three columns Number,
First_operand, and Second_operand.
Number First operand Second operand
1 56 4
2 32 8
3 89 9
4 18 10
5 10 5
o If we want to get the remainder by dividing the numbers of First_operand column by the
numbers of Second_operand column, then we have to write the following query in SQL:
Following are the various comparison operators which are performed on the data
stored in the SQL database tables:
This operator returns TRUE records from the database table if the value of both
operands specified in the query is matched.
Let's understand the below example which explains how to execute Equal
Operator in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id,
Emp_Name, and Emp_Salary.
Let's understand the below example which explains how to execute Equal Not
Operator in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id,
Emp_Name, and Emp_Salary.
Let's understand the below example which explains how to execute Greater
ThanOperator (>) in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id,
Emp_Name, and Emp_Salary.
Emp Id Emp Name Emp Salary
Let's understand the below example which explains how to execute greater than
equals to the operator (>=) in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id,
Emp_Name, and Emp_Salary.
Emp Id Emp Name Emp Salary
This comparison operator checks that the left side operand is lesser than the right side
operand. If the condition becomes true, then this operator in SQL displays the data
which is less than the value of the right-side operand.
Let's understand the below example which explains how to execute less than
operator (<) in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id,
Emp_Name, and Emp_Salary.
Emp Id Emp Name Emp Salary
This comparison operator checks that the left side operand is lesser and equal to the
right side operand.
Let's understand the below example which explains how to execute less than
equals to the operator (<=) in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id,
Emp_Name, and Emp_Salary.
Emp Id Emp Name Emp Salary
Following are the various logical operators which are performed on the data
stored in the SQL database tables:
3. SQL OR operator
5. SQL IN operator
6. SQL NOT operator
1. SELECT,
2. HAVING, and
3. WHERE.
This example consists of an Employee_details table, which has three columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_City.
This example consists of an Employee_details table, which has three columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_City.
Emp Id Emp Name Emp Salary Emp City
SQL OR Operator
The OR operator in SQL shows the record from the table if any of the conditions
separated by the OR operator evaluates to True. It is also known as the conjunctive
operator and is used with the WHERE clause.
Syntax of OR operator:
1. SELECT column1, ...., columnN FROM table_Name WHERE condition1 OR conditio
n2 OR condition3 OR ....... OR conditionN;
Let's understand the below example which explains how to execute OR logical
operator in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_City.
Emp Id Emp Name Emp Salary Emp City
o If we want to access all the records of those employees from the Employee_details table
whose salary is 25000 or the city is Delhi. For this, we have to write the following query in
SQL:
If there is no value in the given range, then this operator shows NULL value.
This example consists of an Employee_details table, which has three columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_City.
Emp Id Emp Name Emp Salary Emp City
SQL IN Operator
The IN operator in SQL allows database users to specify two or more values in a WHERE
clause. This logical operator minimizes the requirement of multiple OR conditions.
This operator makes the query easier to learn and understand. This operator returns
those rows whose values match with any value of the given list.
Syntax of IN operator:
1. SELECT column_Name1, column_Name2 ...., column_NameN FROM table_Name
WHERE column_name IN (list_of_values);
Let's understand the below example which explains how to execute IN logical
operator in SQL query:
This example consists of an Employee_details table, which has three columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_City.
Emp Id Emp Name Emp Salary Emp City
This example consists of an Employee_details table, which has four columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_City.
1. SELECT * FROM Employee_details WHERE NOT Emp_City = 'Delhi' AND NOT Emp
_City = 'Chandigarh';
In this example, we used the SQL NOT operator with the Emp_City column.
The percentage (%) sign is a wildcard which is used in conjunction with this logical
operator.
This operator is used in the WHERE clause with the following three statements:
1. SELECT statement
2. UPDATE statement
3. DELETE statement
This example consists of an Employee_details table, which has four columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_City.
Emp Id Emp Name Emp Salary Emp City
Following are the various set operators which are performed on the similar data
stored in the two SQL database tables:
The data type and the number of columns must be the same for each SELECT statement
used with the UNION operator. This operator does not show the duplicate records in the
output table.
2. UNION
3. SELECT column1, column2 ...., columnN FROM table_Name2 [WHERE conditions];
Let's understand the below example which explains how to execute Union
operator in Structured Query Language:
In this example, we used two tables. Both tables have four columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_City.
Emp Id Emp Name Emp Salary Emp City
Table: Employee_details1
Table: Employee_details2
o Suppose, we want to see the employee name and employee id of each employee from
both tables in a single output. For this, we have to write the following query in SQL:
2. UNION ALL
3. SELECT column1, column2 ...., columnN FROM table_Name2 [WHERE conditions];
Let's understand the below example which explains how to execute Union ALL
operator in Structured Query Language:
In this example, we used two tables. Both tables have four columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_City.
Table: Employee_details1
Table: Employee_details2
o If we want to see the employee name of each employee of both tables in a single output.
For this, we have to write the following query in SQL:
2. INTERSECT
3. SELECT column1, column2 ...., columnN FROM table_Name2 [WHERE conditions];
Let's understand the below example which explains how to execute INTERSECT
operator in Structured Query Language:
In this example, we used two tables. Both tables have four columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_City.
Table: Employee_details1
Table: Employee_details2
Suppose, we want to see a common record of the employee from both the tables in a
single output. For this, we have to write the following query in SQL:
1. SELECT Emp_Name FROM Employee_details1
2. INTERSECT
3. SELECT Emp_Name FROM Employee_details2 ;
In this example, we used two tables. Both tables have four columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_City.
Table: Employee_details1
Emp Id Emp Name Emp Salary Emp City
Table: Employee_details2
Suppose, we want to see the name of employees from the first result set after the
combination of both tables. For this, we have to write the following query in SQL:
1. SELECT Emp_Name FROM Employee_details1
2. MINUS
3. SELECT Emp_Name FROM Employee_details2 ;
These types of operators can be easily operated on the numeric data value of the SQL
table.
Following are the various unary operators which are performed on the numeric
data stored in the SQL table:
This example consists of anEmployee_details table, which has four columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_City.
o Suppose, we want to see the salary of each employee as positive from the
Employee_details table. For this, we have to write the following query in SQL:
This example consists of an Employee_details table, which has four columns Emp_Id,
Emp_Name, Emp_Salary, and Emp_City.
Emp Id Emp Name Emp Salary Emp City
o Suppose, we want to see the salary of each employee as negative from the
Employee_details table. For this, we have to write the following query in SQL:
This example consists of aStudent_details table, which has four columns Roll_No,
Stu_Name, Stu_Marks, and Stu_City.
Emp Id Stu Name Stu Marks Stu City
Following are the two important logical operators which are performed on the
data stored in the SQL database tables:
2. Bitwise OR(|)
This example consists of the following table, which has two columns. Each column holds
numerical values.
When we use the Bitwise AND operator in SQL, then SQL converts the values of both
columns in binary format, and the AND operation is performed on the converted bits.
After that, SQL converts the resultant bits into user understandable format, i.e., decimal
format.
Column1 Column2
1 1
2 5
3 4
4 2
5 3
o Suppose, we want to perform the Bitwise AND operator between both the columns of
the above table. For this, we have to write the following query in SQL:
Bitwise OR (|)
The Bitwise OR operator performs the logical OR operation on the given Integer values.
This operator checks each bit of a value with the corresponding bit of another value.
When we used the Bitwise OR operator in SQL, then SQL converts the values of both
columns in binary format, and the OR operation is performed on the binary bits. After
that, SQL converts the resultant binary bits into user understandable format, i.e., decimal
format.
Column1 Column2
1 1
2 5
3 4
4 2
5 3
SQL Commands
o SQL commands are instructions. It is used to communicate with the database. It is also
used to perform specific tasks, functions, and queries of data.
o SQL can perform various tasks like create a table, add data to tables, drop the table,
modify the table, set permission for users.
o All the command of DDL are auto-committed that means it permanently save all the
changes in the database.
o CREATE
o ALTER
o DROP
o TRUNCATE
Example:
1. CREATE TABLE EMPLOYEE(Name VARCHAR2(20), Email VARCHAR2(100), DOB DA
TE);
b. DROP: It is used to delete both the structure and record stored in the table.
Syntax
1. DROP TABLE table_name;
Example
1. DROP TABLE EMPLOYEE;
c. ALTER: It is used to alter the structure of the database. This change could be either to
modify the characteristics of an existing attribute or probably to add a new attribute.
Syntax:
Syntax:
1. TRUNCATE TABLE table_name;
Example:
1. TRUNCATE TABLE EMPLOYEE;
2. Data Manipulation Language
o DML commands are used to modify the database. It is responsible for all form of
changes in the database.
o The command of DML is not auto-committed that means it can't permanently save all
the changes in the database. They can be rollback.
o INSERT
o UPDATE
o DELETE
a. INSERT: The INSERT statement is a SQL query. It is used to insert data into the row of
a table.
Syntax:
1. INSERT INTO TABLE_NAME
2. (col1, col2, col3,.... col N)
3. VALUES (value1, value2, value3, .... valueN);
Or
Syntax:
1. UPDATE table_name SET [column_name1= value1,...column_nameN = valueN] [W
HERE CONDITION]
For example:
1. UPDATE students
2. SET User_Name = 'Sonoo'
3. WHERE Student_Id = '3'
c. DELETE: It is used to remove one or more row from a table.
Syntax:
1. DELETE FROM table_name [WHERE condition];
For example:
1. DELETE FROM javatpoint
2. WHERE Author="Sonoo";
o Grant
o Revoke
Example
1. GRANT SELECT, UPDATE ON MY_TABLE TO SOME_USER, ANOTHER_USER;
b. Revoke: It is used to take back permissions from the user.
Example
1. REVOKE SELECT, UPDATE ON MY_TABLE FROM USER1, USER2;
These operations are automatically committed in the database that's why they cannot
be used while creating tables or dropping them.
o COMMIT
o ROLLBACK
o SAVEPOINT
a. Commit: Commit command is used to save all the transactions to the database.
Syntax:
1. COMMIT;
Example:
1. DELETE FROM CUSTOMERS
2. WHERE AGE = 25;
3. COMMIT;
b. Rollback: Rollback command is used to undo transactions that have not already been
saved to the database.
Syntax:
1. ROLLBACK;
Example:
1. DELETE FROM CUSTOMERS
2. WHERE AGE = 25;
3. ROLLBACK;
c. SAVEPOINT: It is used to roll the transaction back to a certain point without rolling
back the entire transaction.
Syntax:
1. SAVEPOINT SAVEPOINT_NAME;
o SELECT
a. SELECT: This is the same as the projection operation of relational algebra. It is used to
select the attribute based on the condition described by WHERE clause.
Syntax:
1. SELECT expressions
2. FROM TABLES
3. WHERE conditions;
For example:
1. SELECT emp_name
2. FROM employee
3. WHERE age > 20;
employee Table
Query
It sorts the records automatically in ascending order if we want to show the records in
descending order then we use DECS.
select * from employees ORDER BY salary;
Output
Table 1
Query
select * from employees ORDER BY salary DESC;
Output
table 2
Group By
Group by statement is used to group the rows that have the same value. It is used with
aggregate functions for example AVG(), COUNT(), SUM()etc. One thing is to
remember about the group by clause that the tuples are grouped based on the similarity
between the attribute values of tuples.
Syntax
SELECT function_Name(column_1), column_2
FROM Table_Name
WHERE condition
GROUP BY column_1, col umn_2
ORDER BY column_1, column_2;
Function_Name: Name of the aggregate function, for example:
SUM(), AVG(), COUNT() etc.
Table_Name: Name of the table.
Query
The COUNT() function is used when we need to return the total number of rows that
are stored in the database.So the example for the COUNT() function is
SELECT COUNT(Salary) from employee;
Output
table 3
Query
The AVG() function is used when we need to return the average value of the record.
SELECT AVG(Salary) from employees;
Output
table 4
Query
The SUM() function is used when we need to return the total sum of the record.
SELECT SUM(Salary) from employees;
Output
table 5
In group by clause, the tuples are grouped Whereas in order by clause, the result
based on the similarity between the attribute set is sorted based on ascending or
values of tuples. descending order.
89 A 230
90 B 430
91 C 324
92 D 730
BOOK_ID PRICE
B 430
D 730
89 A Hindi 22000
90 B Hindi 20000
91 C English 25000
Consider, we want the count of books with the count of language > 1. Apply the “Having” clause
to the content in the table.
FROM BOOKS
GROUP BY LANGUAGE
COUNT(BOOK_ID) LANGUAGE
2 Hindi
Filter table based data catering to specific condition Group based data under set condition
Applicable without GROUP BY clause Does not function without GROUP BY clause
Used with single row operations such as Upper, Lower Applicable with multiple row functions such as Sum,
and so on count and so on