Module 3 (SQL Note)
Module 3 (SQL Note)
SQL commands are instructions, coded into SQL statements, which are used to
communicate with the database to perform specific tasks, work, functions and
queries with data.
SQL commands can be used not only for searching the database but also to perform
various other functions like, for example, you can create tables, add data to tables, or
modify data, drop the table, set permissions for users. SQL commands are grouped
into four major categories depending on their functionality:
• Data Definition Language (DDL) - These SQL commands are used for
creating, modifying, and dropping the structure of database objects. The
commands are CREATE, ALTER, DROP, RENAME, and TRUNCATE.
• Data Manipulation Language (DML) - These SQL commands are used for
storing, retrieving, modifying, and deleting data.
These Data Manipulation Language commands are: SELECT, INSERT, UPDATE,
and DELETE.
• Transaction Control Language (TCL) - These SQL commands are used for
managing changes affecting the data. These commands are COMMIT,
ROLLBACK, and SAVEPOINT.
• Data Control Language (DCL) - These SQL commands are used for providing
security to database objects. These commands are GRANT and REVOKE.
• The SQL SELECT command is the only Data Query Language Command over
which whole data extraction and retrieval is dependent.
• The SQL SELECT command is used for “fetching and extracting data from
databases or tables”.
• While fetching data through SELECT command, certain conditions can be attached
in order to generate specific results from the query. Let’s look at the examples now:
SQL/ Sumati/BCA/Trident 1
SQL SELECT Command : Syntax
• There are a number of possible combinations while using SELECT query out of
which some are listed below.
column
SQL SELECT Command : Syntax
OR
SQL/ Sumati/BCA/Trident 2
SQL SELECT Command : Example
• We will continue with the database i.e db_school and table i.e student_details we
had created earlier and try to give a possible example for each of the above
mentioned syntax available. Considering the table and details we had:
• Table : student_details
Output:
SQL/ Sumati/BCA/Trident 3
Query-2 : SELECT name from student_details;
Output:
Output:
Output:
OPERATORS
Operators Description
+ Addition
– Subtraction
* Multiplication
/ Division
SQL/ Sumati/BCA/Trident 4
Comparison Operators
• The comparison operators are used in such conditions that compare one expression to
another.
• The format of the operator in the WHERE clause is WHERE Expression OPERATOR
VALUE.
Symbol Name
= Equality Operator
Query:
Output:
Query:
SQL/ Sumati/BCA/Trident 5
Output:
Logical Operators
Logical Operators combine the results of two-component conditions to produce a single result.
Logical operators provided by ORACLE are:
Symbol Name
AND Operator
OR Operator
NOT Operator
SQL/ Sumati/BCA/Trident 6
• The lower limit should be declared first.
Query:
SELECT Ename, Sal, Job FROM Emp WHERE sal BETWEEN 1000 AND 6000;
Output:
IN Operator
Query:
IS NULL Operator
Query:
Output:
SQL/ Sumati/BCA/Trident 7
Query:
SELECT Ename, Sal, Comm FROM Emp WHERE Comm IS NOT NULL;
Output:
LIKE Operator
The LIKE operator is used in character string comparisons with pattern matching.
With the LIKE operator, you can compare a value to a pattern rather than to a constant.
Wildcard Explanation
Example 1
SQL/ Sumati/BCA/Trident 8
Example 3
• Once the tables in the databases are created, it’s now time to insert values into these
tables. This can be done using SQL INSERT command. INSERT command can be
used in two different types. Both of them are explained below. Let’s look at its
syntax first :
SQL/ Sumati/BCA/Trident 9
SQL INSERT Command : Syntax
OR
SQL/ Sumati/BCA/Trident 10
Query-2 : INSERT Into teacher_details Values(102, ‘Anoop’, ‘PGT’);
• In this way, one can insert as much data as possible in the database.
• The thing one must remember while inserting the data in the database is the order
of columns. If value of roll_no is inserted into name or vice-versa, the query will not
execute.
• Also, values should be inserted according to the data types mentioned while creating
the tables.
• SQL UPDATE command is a must have command while dealing with large data set.
If by chance, any values in the table are inserted incorrectly, UPDATE command is
there to help you out.
• Also, with the help of SQL Clauses, modification on specific rows/values can also be
done.
SQL/ Sumati/BCA/Trident 11
SQL UPDATE Command : Example
Table : student_details
Table : teacher_details
Example-1 : Now if we wish to update marks of student “SAURAV”. Then, it can be done
by executing the below query.
Output :
Example-2 : If we wish to update the name of the teacher. Then it can be done by executing
below query.
SQL/ Sumati/BCA/Trident 12
Output :
• The SQL DELETE Command is a type of SQL SDML Command and is used to
delete pre-existing records or values or rows of the tables present in the database.
• The advantage of using SQL DELETE Command is, only the values or records
from table gets deleted and the overall structure(containing attributes) remains
untouched. Let’s check the syntax first and then we will try to implement this
command with an example.
• The syntax for SQL DELETE Command is pretty simple. There are two possible
basic syntax based on conditions. Below is their illustration.
OR
SQL/ Sumati/BCA/Trident 13
SQL DELETE Command : Syntax
Table : student_details
Example-2 : If we wish to delete a particular row from the student_details, it can be done
by executing below query.
NOTE : As the structure of table remains untouched even after deletion of table data. If
we need to insert values in the table again, it can be done without creating a new table and
by directly inserting values to the table through INSERT command.
• SQL TRUNCATE Command is a type of SQL DDL command and is used to delete
the pre-existing tables from the databases.
SQL/ Sumati/BCA/Trident 14
• The difference between SQL DELETE and SQL TRUNCATE Command is, there is
no room for deleting specific values/rows from the table with the help of
TRUNCATE command. Only the whole table can be deleted and not the specific
rows/values.
Table : student_details
Table : teacher_details
Example-1 : We wish to delete the student_details table. It can be done by executing below
query.
SQL/ Sumati/BCA/Trident 15
Query : TRUNCATE Table student_details;
• SQL DROP Command is also a SQL DDL Command and is used to perform same
functionality as TRUNCATE command. i.e. to delete the existing table completely
from the database leaving nothing behind.
• It means, all the values, attributes, rows, column and overall structure of the table is
deleted completely.
• If we wish to insert values in the same table, it need to be recreated first and then
only the values can be inserted.
• DROP Command once executed cannot be rolled back. It means, once the table is
deleted, it cannot be retrieved again.
• The syntax for SQL DROP Command is quiet similar to that of TRUNCATE
command except for the DROP keyword that is used in DROP command.
SQL/ Sumati/BCA/Trident 16
Table : student_details
Table : teacher_details
Example-1 : We wish to delete the student_details table. It can be done by executing below
query.
NOTE : As the structure of table is deleted completely, If we need to insert values in the
table again, it cannot be done without creating a new table. Hence, new table needs to
created first and then values to the table can be inserted through INSERT command.
• The syntax of ALTER Command varies depending upon the type of alteration the
user wants. The syntax for each is illustrated below.
SQL/ Sumati/BCA/Trident 17
SQL ALTER Command : Types
• Consider the table of student_details over which all the above commands will be
executed.
Table : student_details
Output :
SQL/ Sumati/BCA/Trident 18
Note : The values in column “Location” are left blank because had added the column to
the table and not inserted the values in it.
Output : You won’t see any change in view of table. But, while inserting new values, only
character values will be inserted in the “Name” column.
Output :
Output :
SQL/ Sumati/BCA/Trident 19
Note : A Primary Key is an attribute of a table with the help of which each data record
present in the table can be uniquely identified. To know more about, please refer KEYS IN
DBMS.
• SQL Constraints are the “Limits or Rules” that the users can specify while creating
the tables and inserting values in it. Constraints means “Restrictions” in data which
ensures better performance of the databases.
• Also, SQL Constraints restricts the type of data that is to be inserted in the table of
the database allowing better results while executing SQL queries.
• The SQL Constraints that can be used are listed and explained below.
SQL/ Sumati/BCA/Trident 20
SQL Constraints
SQl Constraints are rules used to limit the type of data that can go into a table, to maintain the
accuracy and integrity of the data inside table.Constraints can be divided into following two types,
With Table level Contraint,we can define constraint for multiple columns where as for
Column level (inline) we can define constraint only for specific column only.
Column-level constraints refer to a single column in the table and do not specify a
column name (except check constraints). ... Table-level constraints refer to one or
more columns in the table. Table-level constraints specify the names of the columns
to which they apply.
Constraints are used to make sure that the integrity of data is maintained in the database. Following
are the most used constraints that can be applied to a table.
• NOT NULL
• UNIQUE
• PRIMARY KEY
• FOREIGN KEY
• CHECK
• DEFAULT
NOT NULL constraint restricts a column from having a NULL value. Once NOT NULL constraint is
applied to a column, you cannot pass a null value to that column. It enforces a column to contain a
proper value. One important point to note about NOT NULL constraint is that it cannot be defined at
table level.
SQL/ Sumati/BCA/Trident 21
Example using NOT NULL constraint
CREATE table Student(s_id int NOT NULL, Name varchar(60), Age int);
The above query will declare that the s_id field of Student table will not take NULL value.
UNIQUE Constraint
UNIQUE constraint ensures that a field or column will only have unique values. A UNIQUE
constraint field will not have duplicate data. UNIQUE constraint can be applied at column level or
table level.
CREATE table Student(s_id int NOT NULL UNIQUE, Name varchar(60), Age int);
The above query will declare that the s_id field of Student table will only have unique values and
wont take NULL value.
The above query specifies that s_id field of Student table will only have unique value.
SQL/ Sumati/BCA/Trident 22
Primary key constraint uniquely identifies each record in a database. A Primary Key must contain
unique value and it must not contain null value. Usually Primary Key is used to index the data inside
the table.
CREATE table Student (s_id int PRIMARY KEY, Name varchar(60) NOT NULL, Age int);
Example
Let's look at an example of how to add a unique constraint to an existing table in Oracle using the
ALTER TABLE statement.
SQL/ Sumati/BCA/Trident 23
Example
Let's look at an example of how to remove a unique constraint from a table in Oracle.
CHECK Constraint
CHECK constraint is used to restrict the value of a column between a range. It performs check on
the values, before storing them into the database. Its like condition checking before saving data into
a column.
Age int);
The above query will restrict the s_id value to be greater than zero.
SQL/ Sumati/BCA/Trident 24
Columnname datatype DEFAULT 'defaultvalue' );
FOREIGN KEY is used to relate two tables. FOREIGN KEY constraint is also used to restrict actions
that would destroy links between tables. To understand FOREIGN KEY, let's see it using two table.
Customer_Detail Table :
Order_Detail Table :
SQL/ Sumati/BCA/Trident 25
10 Order1 101
11 Order2 103
12 Order3 102
In Customer_Detail table, c_id is the primary key which is set as foreign key in Order_Detail table.
The value that is entered in c_id which is set as foreign key in Order_Detail table must be present
in Customer_Detail table where it is set as primary key. This prevents invalid data to be inserted
into c_id column of Order_Detail table.
In this query, c_id in table Order_Detail is made as foriegn key, which is a reference of c_id column
of Customer_Detail.
There are two ways to maintin the integrity of data in Child table, when a particular record is deleted
in main table. When two tables are connected with Foriegn key, and certain data in the main table is
SQL/ Sumati/BCA/Trident 26
deleted, for which record exit in child table too, then we must have some mechanism to save the
integrity of data in child table.
• On Delete Cascade : This will remove the record from child table, if that value of foriegn key is
deleted from the main table.
• On Delete Null : if a record in the parent table is deleted, then the corresponding records in the
child table will have the foreign key fields set to null..
• If we don't use any of the above, then we cannot delete data from the main table for which data
in child table exists. We will get an error if we try to do so.
SQL/ Sumati/BCA/Trident 27
ALTER TABLE products
ADD CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
ON DELETE CASCADE;
Syntax
To RENAME A COLUMN in an existing table, the Oracle ALTER TABLE syntax is:
Example
Let's look at an example that shows how to rename a column in an Oracle table using
the ALTER TABLE statement.
SQL/ Sumati/BCA/Trident 28
For example:
Rename table
Syntax
RENAME TO new_table_name;
Example
Let's look at an example that shows how to rename a table in Oracle using the ALTER
TABLE statement.
For example:
RENAME TO contacts;
• SQL functions are special classical functions that are used to perform specific tasks
when combined in with SQL queries. They are basically arithmetic functions.
SQL/ Sumati/BCA/Trident 29
• They are used in tables with columns having numerical values. There exists five
SQL functions which are majorly used and all of them are listed and explained
below.
• The “SUM” function as the name suggests, is used to calculate sum for a particular
column. Below is the syntax and example.
Example : Consider the student_details table. We can find the total sum of marks of
students by using below query.
Table : student_details
Output :
SQL/ Sumati/BCA/Trident 30
SQL Functions : AVG
• The AVG (Average) function as the name suggests is used to calculate average for a
particular column containing numeric values.
Example : Consider the student_details table. We can calculate the average of marks for
the students using “AVG” function using below query.
Table : student_details
Output :
• The "COUNT" function calculates the number of rows that exists in a column
which follows a particular condition.
Example : Consider the student_details table. If we want to “COUNT” the total number of
students present in the table, it can be done using below query.
Table : student_details
SQL/ Sumati/BCA/Trident 31
Query : SELECT COUNT(Roll_No) From student_details;
Output :
SQL Functions : MIN
• The SQL “MIN” function is used to return smallest possible value from a particular
column containing numeric values.
Example : Consider the student_details table. If we want to select the minimum marks of a
student, it can be done by executing below query.
Table : student_details
Output :
• The SQL “MAX” function is used to return largest possible value from a particular
column containing numeric values.
SQL/ Sumati/BCA/Trident 32
Example : Consider the student_details table. If we want to select the maximum marks of
a student, it can be done by executing below query.
Table : student_details
Output :
The GROUP BY statement groups rows that have the same values into summary rows, like "find
the number of customers in each country".
The GROUP BY statement is often used with aggregate functions (COUNT, MAX, MIN, SUM,
AVG) to group the result-set by one or more columns.
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
SQL/ Sumati/BCA/Trident 33
Demo Database
Below is a selection from the "Customers" table in the Northwind sample database:
The following SQL statement lists the number of customers in each country:
Example
SQL/ Sumati/BCA/Trident 34
Oracle HAVING Example: (with GROUP BY MIN function)
Employees table:
2. ( "EMP_ID" NUMBER,
3. "NAME" VARCHAR2(4000),
4. "AGE" NUMBER,
5. "DEPARTMENT" VARCHAR2(4000),
6. "SALARY" NUMBER
7. )
8. /
1. SELECT department,
3. FROM employees
4. GROUP BY department
SQL/ Sumati/BCA/Trident 35
5. HAVING MIN(salary) < 15000;
Output
1. SELECT department,
3. FROM employees
4. GROUP BY department
Output:
• SQL JOINS are the special clauses that are used to combine multiple tables present
in a database on the basis of some common attributes present in those tables.
• The SQL JOINS has the ability of combining two or more data tables/tuples into a
single table/table only if the following conditions are satisfied.
• The common attributes are compared using SQL Operators based upon the
required conditions. The most oftenly used operator is the “=” (Equal To) symbol.
SQL/ Sumati/BCA/Trident 36
• Also, SQL Joins uses “ON” clause. There are Five basic SQL Joins each of whose
syntax and examples are explained in this chapter.
• The INNER JOIN which is also known as “SIMPLE JOIN or EQUIJOIN” is the
most commonly used join in SQL. Queries equipped with INNER JOIN when
executed returns all the rows which are present in the tables corresponding to the
common attribute.
SQL/ Sumati/BCA/Trident 37
Table : student_details
Table : student_result
Output :
• The NATURAL JOIN is similar to INNER JOIN. The only difference is, redundant
columns present in INNER JOINS are removed when NATURAL JOIN is used.
• It works only if, one attribute or more than one attributes are common between the
joining/participating relations.
SQL/ Sumati/BCA/Trident 38
Query : SELECT * From student_details NATURAL JOIN student_result;
Output
SYNTAX: SYNTAX:
SELECT * SELECT *
FROM table1 NATURAL JOIN FROM table1 INNER JOIN table2 ON
3. table2; table1.Column_Name = table2.Column_Name;
SQL/ Sumati/BCA/Trident 39
• To implement LEFT OUTER JOIN, at least one entity needs to be common in the
relations. All the attributes/tuples present in the left relation are recorded in the
resulting relation along with those which are commonly present in the right relation.
• If in case any tuple in left relation does not matches with the tuple in right
relation, NULL value will be displayed against that tuple in the resulting relation.
For Example : Consider the tables student_details and student_result. Now, if we want to
implement left outer join on these relations, the result will look like:
Query : SELECT Roll_No, Name, Address, Subject, Marks From Student_Details LEFT
OUTER JOIN Student_Result ON Student_Details.Roll_No = Student_Result.Roll_No;
• The RIGHT OUTER JOIN is completely similar to left outer join except the
resulting relation will include all the tuples from relation present on right hand
relation.
• Also, NULL value will be displayed against the tuple which doesn’t matches up with
the left side relation.
SQL/ Sumati/BCA/Trident 40
For Example : Consider the tables Student_Details and Student_Result. Now, if we want to
implement right outer join on these relations, the result will look like:
Query : SELECT Roll_No, Name, Address, Subject, Marks From Student_Details RIGHT
OUTER JOIN Student_Result ON Student_Details.Roll_No = Student_Result.Roll_No;
• In FULL OUTER JOIN, both the relations are merged together which results in a
relation consisting of all the tuples.
For example : Consider the tables Student_Details and Student_Result. Now, if we want to
implement full outer join on these relations, the result will look like:
Query : SELECT Roll_No, Name, Address, Subject, Marks From Student_Details FULL
OUTER JOIN Student_Result ON Student_Details.Roll_No = Student_Result.Roll_No;
SQL/ Sumati/BCA/Trident 41
NOTE : In the above description of various joins, some symbols are used in the screenshots
of examples. They all have some certain meaning.
1. ⋈: Natural Join
A self join is a regular join but the table is joined with itself. This is useful when we want to
compare rows within the same table.
WHERE condition;
o You can use self join to find employee names along with their manager names.
SQL/ Sumati/BCA/Trident 42
SELECT E1.emp_name AS Employee, E2.emp_name AS Manager
1 Alice NULL
2 Bob 1
3 Carol 1
Employee Manager
Bob Alice
Carol Alice
SQL/ Sumati/BCA/Trident 43