Unit-2 Basics of SQL
Unit-2 Basics of SQL
Unit-2 Basics of SQL
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.
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.
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.
It has a maximum length of 8000 characters. It contains variable-length non-
varchar
unicode characters.
It has a maximum length of 2,147,483,647 characters. It contains variable-length
text
non-unicode characters.
5. Date and time Data type: The subtypes are given below:
SQL OPERATOR
An operator is a reserved word or a character used primarily in an SQL statement's WHERE
clause to perform operation(s), such as comparisons and arithmetic operations. These
Operators are used to specify conditions in an SQL statement and to serve as conjunctions for
multiple conditions in a statement. There are various types of SQL operator:
SQL Arithmetic Operators: Let's assume 'variable a' and 'variable b'. Here, 'a' contains 20
and 'b' contains 10.
SQL Comparison Operators: Let's assume 'variable a' and 'variable b'. Here, 'a' contains 20
and 'b' contains 10.
SQL Logical Operators: There is the list of logical operator used in SQL
Operator Description
ALL It compares a value to all values in another value set.
Some It compares a value to some values in another value set.
AND It allows the existence of multiple conditions in an SQL statement.
ANY It compares the values in the list according to the condition.
BETWEEN It is used to search for values that are within a set of values.
IN It compares a value to that specified list value.
NOT It reverses the meaning of any logical operator.
OR It combines multiple conditions in SQL statements.
EXISTS It is used to search for the presence of a row in a specified table.
LIKE It compares a value to similar values using wildcard operator.
IS NULL The NULL operator is used to compare a value with a NULL value.
The UNIQUE operator searches every row of a specified table for uniqueness
UNIQUE
(no duplicates).
SQL COMMAND
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. SQL can perform various tasks like
create a table, add data to tables, drop the table, modify the table, set permission for users.
DDL (Data Definition Language) : DDL or Data Definition Language actually consists ofthe
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
database objects in database.
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;
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 change the DATA TYPE of a column in a table is as follows.
ALTER TABLE command to add a NOT NULL constraint to a column in a table is as follows.
DML (Data Manipulation Language) : The SQL commands that deals with the manipulation
of data present in database belong to DML or Data Manipulation Language and this includes
most of the SQL statements.
Prof. Dnyandeo Khemnar Page 8
1. SELECT – is Data Manipulation Language command used to retrieve data from the tables
of selected database. It retrieves the data and displays the retrieved data on console.
Syntax:
SELECT expressions FROM TABLES WHERE conditions;
For example:
SELECT emp_name FROM employee WHERE age > 20;
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'
DCL (Data Control Language) : DCL includes commands such as GRANT and REVOKEwhich
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;
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;
VIEWS IN SQL
Views in SQL are a virtual table. A view also contains rows and columns. They have their own
existence in database But they don’t save any records in a view. To create the view, we can
select the fields from one or more tables present in the database. A view can either have
specific rows based on certain condition or all the rows of a table. we can add SQL functions,
WHERE, and JOIN statements to a view and present the data as if the data were coming from
one single table.
Student_Detail Student_Marks
1. Creating view: A view can be created using the CREATE VIEW statement. We can create
a view from a single table or multiple tables.
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;
2. Creating View from multiple tables: View from multiple tables can be created by simply
include multiple tables in the SELECT statement.
Example, a view is created named MarksView from two tables Student_Detail and
Student_Marks.
NESTED QUERY(subquery)
A Subquery or Inner query or a Nested query is a query within another SQL query and
embedded within the WHERE clause. A subquery is used to return data that will be used in the
main query as a condition to further restrict the data to be retrieved. Subqueries can be used
with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <,
>, >=, <=, IN, BETWEEN, etc. sub queries can retrieve the data from single or multiple tables.
1. Sub queries with the SELECT Statement: Subqueries are most frequently used with the
SELECT statement. The basic syntax is as follows
SQL> SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY
> 4500) ;
3. Subqueries with the INSERT Statement: Sub queries also can be used with INSERT
statements. The INSERT statement uses the data returned from the subquery to insert into
another table. The selected data in the sub query can be modified with any of the character,
date or number functions. The basic syntax is as follows.
INSERT INTO table_name [(column1 [, column2 ])] Operator (SELECT [ *|column1 [, column2
] FROM table1 [, table2 ] [ WHERE VALUE OPERATOR ])
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.
5. Subqueries with the DELETE Statement: The subquery can be used in conjunction with
the DELETE statement like with any other statements mentioned above. The basic syntax is as
follows.
SQL> DELETE FROM CUSTOMERS WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP
WHERE AGE >= 27 );
This would impact two rows and finally the CUSTOMERS table would have the following
records.
So suppose query is to find 50 , it will have to read 49 records as a linear search. Refer the
following image.
When we apply indexing, the query will quickly find out the data without
reading each one of them just by eliminating half of the data in each traversal like a binary
search. The mysql indexes are stored as B-tree where all the data are in leaf node.
CREATE TABLE student ( id INT PRIMARY KEY, name VARCHAR(50) NOT NULL, gender VAR
CHAR(50) NOT NULL, DOB datetime NOT NULL, total_score INT NOT NULL, city VARCHAR(5
0) NOT NULL)
in the “student” table we have set primary key constraint on the “id” column. This
automatically creates a clustered index on the “id” column. To see all the indexes on a
particular table execute “sp_helpindex” stored procedure. This stored procedure accepts the
name of the table as a parameter and retrieves all the indexes of the table. The following
query retrieves the indexes created on student table.
USE schooldb
EXECUTE sp_helpindex student
Non-Clustered Indexes: A non-clustered index doesn’t sort the physical data inside the table.
In fact, a non-clustered index is stored at one place and table data is stored in another place.
This is similar to a textbook where the book content is located in one place and theindex
is located in another. This allows for more than one non-clustered index per table. It is
important to mention here that inside the table the data will be sorted by a clustered index.
However, inside the non-clustered index data is stored in the specified order. The index
contains column values on which the index is created and the address of the record that the
column value belongs to. When a query is issued against a column on which the index is
created, the database will first go to the index and look for the address of the corresponding
row in the table. It will then go to that row address and fetch other column values. It is due to
this additional step that non-clustered indexes are slower than clustered indexes.
use schooldb
The above script creates a non-clustered index on the “name” column of the student table. The
index sorts by name in ascending order. As we said earlier, the table data and index will be
stored in different places. The table records will be sorted by a clustered index if there is one.
The index will be sorted according to its definition and will be stored separately from the
table.Create Index statement: It is used to create an index on a table. It allows duplicate
value.
ALTER command to add and drop INDEX: There are four types of statements for adding indexes
to a table.
ALTER TABLE tbl_name ADD PRIMARY KEY (column_list) − This statement adds
a PRIMARY KEY, which means that the indexed values must be unique and cannot be NULL.
ALTER TABLE tbl_name ADD INDEX index_name (column_list)− This adds an ordinary
index in which any value may appear more than once.
Displaying INDEX Information: You can use the SHOW INDEX command to list out all
the indexes associated with a table
SQL CLAUSES
Clauses are used to apply some condition or constraints on the query The following are the
various SQL clauses:
Where Clause
Order By Clause
Group By Clause
Having Clause
Distinct Clause
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.
MySQL WHERE Clause with AND condition: In this example, we are retrieving data from the
table "officers" with AND condition.
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;
Example: Sorting Results in Descending Order
SELECT * FROM CUSTOMER ORDER BY NAME DESC;
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
MySQL HAVING Clause: MySQL HAVING Clause is used with GROUP BY clause. Italways
returns the rows where condition is TRUE.
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;
SET OPERATIONS:
SQL supports few Set operations which can be performed on the table data. These are used to get
Prof. Dnyandeo Khemnar Page 18
meaningful results from data stored in the table, under different special conditions. Or
The SQL Set 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 First table, The Second table,
ID Name ID Name
1 Abhi 2 adam
2 Adam 3 Chester
UNION Operation: 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.
Select * from First Union Select * from Second
The result set table will look like,
ID NAME
1 abhi
2 adam
3 Chester
UNION ALL: This operation is similar to Union. But it also shows the duplicate rows.
ID NAME
2 adam
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 < SOME B TRUE A < ALL B TRUE
A <= SOME B TRUE A <= ALL B TRUE
A >= SOME B TRUE A >= ALL B FALSE
A > SOME B FALSE A > ALL B FALSE
A <> SOME B TRUE A <> ALL B FALSE
A = SOME B TRUE A = ALL B FALSE
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’)
SQL JOINS
The SQL Joins clause is used to combine records from two or more tables in a database. A
JOIN is a means for combining fields from two tables by using values common to each. A SQL
Join statement is used to combine data or rows from two or more tables based on a common
field between them.
Let us Discus Different types of Joins with two tables Order & Customer
1. INNER JOIN
2. LEFT JOIN
3. RIGHT JOIN
4. FULL JOIN
Table 1: Customer
Table 2: Order
order_id 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
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 t1.attribute, t2.attribute from Table1 t1 INNER JOIN Table t2 ON
t1.matching_Column= t2.matching_Column
2. LEFT JOIN: it is also called as Left Outer Join. This join returns all the rows of the table on
the left side of the join and matching rows for the table on the right side of join. The rows for
which there is no matching row on right side, the result-set will contain null. LEFT JOIN is also
known as LEFT OUTER JOIN.
Syntax: Select t1.attribute, t2.attribute from Table1 t1 LEFT JOIN Table t2 ON
t1.matching_Column= t2.matching_Column
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
4. FULL JOIN: FULL JOIN creates the result-set by combining result of both LEFT JOIN and
RIGHT JOIN. The result-set will contain all the rows from both the tables. The rows for which
there is no matching, the result-set will contain NULL values.
Syntax: Select t1.attribute, t2.attribute from Table1 t1 FULL JOIN Table t2 ON
t1.matching_Column= t2.matching_Column
3.3 TUPLE VARIABLE: A tuple variable is variable that takes on tuples of a particular relation
schema as values. That is, every value assigned to a given tuple variable has the same number and type
of fields. Consider the Table
order_date Sale_of_Day
07/04/1776 $313.06 The Output of this will look like this where as
05/23/1784 $189.50
Sale_of_Day is a tuple variable.
07/21/1795 $25.50
11/27/1787 $14.40