2. 2 STRUCTURED QUERY LANGUAGE (SQL)
STRUCTURED QUERY LANGUAGE (SQL)
SQL: it is a set of commands that lets to access a relation database. It is a standard
interference for many relational databases. it has several simple commands for data
definition , access and manipulation. It is set oriented. i.e. user can perform
command on a group of data rows or one row . SQL is a non-procedural. To access
data user need only to name the table and the columns .No need of a describing
method.
SQL HISTORY: SQL begin with a paper published in 1970 by E.F.CODD, a
mathematician working at IBM Research Laboratory in San Josc, California. In this
paper “A relational model of data for large shared data banks”.
CODD formulated the principle of relational system for managing a database and
describing relational algebra for organizing data into tables.
Two years later Chamberlin and others developed a version of language,
SEQEL/2 and shortly after that IBM built a prototype system called ‘Sys R’ that
implemented most of its features. Around 1980the name was changed to SQL.
ADVANTAGES OF SQL:-
1. Acceptance: The American National Standard Institute (ANSI) has approved
SQL.The International Standard Organization (ISO) and the department of
defense also supports SQL.A version of SQL is available in most of companies.
2. Powerful: SQL is complete database language. So user can use it for data
defining or definition, data control, transaction management. SQL commands
are simple to use in three basic forms, but they have the flexibility to do
complex operations.
3. Ease of Use: People can easily access and manipulate data without being
involved with the physical organization and storage complexities of the data.
CREATION OF DATABASE:
A database is collection of logically related data where data is nothing but known
facts that can be recorded and has implicit meaning. A database can be any size for
example Library database, student database…..etc.
To create the databases we use the command called CREATE.
In order to communicate with the database, SQL supports the following languages.
1. DDL: Data Definition Language.
2. DML: Data Manipulation Language.
<SQL by Prasad>
3. 3 STRUCTURED QUERY LANGUAGE (SQL)
3. TCL: Transaction Control Language.
DDL: It is used to create objects (tables), alter the structure of the objects (tables)
and also to drop the objects (tables) created. The concept creating to the DDL is
explained below.
TABLE DEFINITION: A table is a unit of storage that holds the data in the rows and
columns. The DDL used for table definition can be classified into the following form,,
COMMANDS IN DDL:
1. CREATE TABLE Command
2. ALTER Command
3. DROP Command
4. TRUNCATE Command
5. DESC Command
Now consider these Commands one by one;
1. CREATE Command:
Syntax;
Create table <table name> (column1, column2 …columnn);
EX; create table emp (emp_id number(4), name varchar(15), age number(2),
salary number(5));
Defining a database is nothing but giving a name to an eventual collection of
associated data. A single database can contains all data associated with one
application or with group of related applications. Collecting data into single
database allows the user to access the data with one operation.
In database the data is stored in the form of rows and columns i.e. nothing but
tables (relational model). A database contains one or more tables. Each table has a
name & contains a specific number of columns (vertical) & unordered rows
(horizontal). Each column in arrow is related in some way to the other column in the
same row.
Foe Example: consider the below table.
Cust_no contact credit ------------- Columns
1564 john 3000
1243 smith 1500
1345 joe 2000
1123 jack 2500 ------------ Rows
Fig: cust table
<SQL by Prasad>
4. 4 STRUCTURED QUERY LANGUAGE (SQL)
Each column has a name & a datatype. Each column contains a data value at the
intersection of row & a column.
In a table,
i) We should specify unique column name
ii) We should specify proper data type along with is width.
Rules For creating a table.
1. While naming the table first letter should be alphabet.
2. Oracle reserved words cannot be used to name a table.
3. Maximum length for table is 30 characters.
4. Two different tables should not have the same name.
5. Underscore (_), minus(-),numerals & letters are allowed but not blank space &
single quotes
2. ALTER Command:
In some situations, there may be need to change the structure of the table. This
change could be either to modify an existing attribute characteristic or probably
to add a new attribute character.
Syntax;
Alter table <table_name> modify <column_definition>;
EX: alter table emp modify (ename varchar(20));
IN this alter command the length of the field name changed to 20 from 15. We can
decrease the length of an existing column datatype provided the table is empty. No
such conditions are imposed while increase the length of an existing column.
Alter table <table_name> add(column_definition);
To above command adds new column to an existing table.
Ex; alter table emp add(address varchar(30));
This command adds a new field called ‘address’ to the emp table.
3. TRUNCATE Command:
<SQL by Prasad>
5. 5 STRUCTURED QUERY LANGUAGE (SQL)
If there is no further use of records stored in a table & structure has to be
retained then the records alone can be deleted, which can done through the
Command called ‘truncate’.
Syntax;
Truncate table <table_name>;
Ex; truncate table emp;
This deletes the all the rows of the emp table but not the structure of the table.
4. DESC Command or VIEW Command:
If the user wants to view the str (structure) of the table or the description of the
table then following command helps to achieve the same.
Syntax: desc <table_name>;
Ex; desc emp;
This command list the column of the emp table along with their datatypes or it
gives the description of the table.
5. DROP Command:
This command is used to delete the entire table i.e. entirely remove from
database. In other words this command erases the all contents of the table and
table name which was specified.
Syntax: drop table <table_name>;
Ex; drop table emp;
Where it deletes the table emp from database.
**********************************************************************************
************
DML (Data Manipulation Language): DML Commands are most frequently used
SQL Commands They are used to query & manipulate existing objects like tables.
COMMANDS IN DML:
1. INSERT Command
2. SELECT Command
3. UPDATE Command
4. DELETE Command
Now consider these Commands one by one;
1. INSERT Command:
Once creation of the table is completed, it remains a skeletal structure unless it is
populated with rows. The insert command is used to add one or more rows to a
table. While using this command the values are separated by comma’s & datatypes
<SQL by Prasad>
6. 6 STRUCTURED QUERY LANGUAGE (SQL)
varchar2,char,date,long,number are enclosed in single quotes. The values must be
entered in the same order as they are defined in the table.
Syntax: insert into <table_name> values (value_list);
Ex: insert into emp values(123,‘prasad’,22,15000);
The above command inserts one row with the values 123,‘prasad’,22,15000 into
the table emp. Here we are inserting the values for one row at a time. This is
called SINGLE INSERTION.
MULTIPLE INSERTION of rows is also possible with the below syntax.
Insert into emp values(&emp_id,‘&name’,&age,&salary);
Using this insertion statement we can insert any number of rows into the table.
Multiple is nothing but using the single insert command we can insert any
number of rows into the table.
In some cases, we don’t want to enter the value for one or two columns in the
table. To do this we can simply enter the value as ‘NULL’ for the specified
column.
Inserting data value into the tables into the table is same as inserting the
character values, i.e. by enclosing it within single quotes.
Ex: insert into emp values(123,‘prasad’,22,15000);
2. SELECT Command:
SELECT supports the data retrieval. Data retrieval allows a user or an application
program to retrieve stored data from the database & use it.
The select statement retrieves data from a database & returns it to you in the
form of query result. Using ‘select’ we can view the current into in the tables. With
the ‘select’ statement we can do the following,
Displaying the entire Column from a table:
Display calculated information from tables, like avg or sum of column.
Values(computed fields)
Combine information from two or more tables.
SET OPERATORS:
The general form of ‘select’ statement is,,
Syntax: Select <column_name> from <table_name>;
Ex: select name from emp;
The above statement is interpreted as,
SELECT(What):--
One or more column may be selected from a table. If you select more than one
column then the column_name must be separated by Comma’s.
<SQL by Prasad>
7. 7 STRUCTURED QUERY LANGUAGE (SQL)
FROM(Where):--
Table name from which the columns are to be selected.
a) Displaying all the columns from a table:
‘Select’ & ‘from’ are the two mandatory words in ‘select’ query. A special ‘select’
qualifies is asterisk (*) which is used if the user wishes to select all the columns
from a table.
Syntax: select * from <table_name>;
Ex: select * from emp;
This select statement will display all rows of the table emp.
Controlling Column Order: The order in which the column names are specified
in select command determines the order in which the columns are displayed.
Ex: select emp_id,name,salary from emp;
b) Displaying Calculated into from table(Computed fields or Conditional
retrieval):
This section explains about how one can select specific rows from a table & how
to select rows that specify singular or multiple search condition.
Ex: Consider that we want to know the salaries of emp who get Rs.10,000 &
above. To achieve this we can use ‘where’ clause in the select statement as
follows,,,
Select name from emp where salary >=10000;
The output of the above query will be displays the names of employees who
receives the salaries 10000 & above.
Syntax:
select <column_name> from <table_name> where condition;
In where clause we can include Relational operators & logical operators.
Relational Operators: < , > , >= , <= , = , <>
Logical Operators: AND, OR, NOT.
Ex: select emp_id,name from emp where name=’prasad’ and salary=15000;
Select with distinct clause:
Consider name column from emp table, whose values are given below;
name
aaa bbc
bac ccc
abc
aaa
<SQL by Prasad>
8. 8 STRUCTURED QUERY LANGUAGE (SQL)
Some columns in table have been repeated twice. They are called duplicate
values while displaying the duplicate values must be eliminated. To do this we use
the distinct clause in select command.
Syntax:
Select distinct <column_name> from <table_name>;
Ex; select distinct name from emp;
Output:
name
aaa bbb
bac bbc
abc
NOTE: Duplicate values have been removed with the use of distinct clause.
ORDER by clause(Sorting):
We have seen the queries that display rows in the order that they have been defined
at the time of creation of the table. The order can be controlled in which the rows of
the table are displayed by using order by clause. In the query with the order by
clause one can order the rows in ascending or descending order. The order by clause
by default places the rows in ascending order.
Ex; select emp_id,name from emp order by emp_id;
If emp_id has values
20
50
30
40
Then the Output is below format
emp_id name
20 a
30 b
40 c
50 d
This query will sort the values in ascending order because the default order is
ascending order.
Ex: select emp_id,name from emp order by emp_id desc;
Output:
emp_id name
50 d
40 c
<SQL by Prasad>
9. 9 STRUCTURED QUERY LANGUAGE (SQL)
30 b
20 a
3. UPDATE Command:
UPDATE modifies the values of one or more columns in selected rows of a table.
The table to updated is named in the statement. The where clause selects the
rows of the table to modified. The set specifies which columns are to be updated
& calculates the new values from them.
Syntax:
Update <table_name> set <column_name1> =
<value1>,<column_name2> = <value2>………where <logical_expression>;
UPDATE sets each column name (field) equal to corresponding value in the row
selected by the logical expression. Update will change the values on all table rows
that specify where condition.
For example, suppose if salary has the value of 15000 & want to change (update)
it to 20000 then using update command is update emp set salary=20000
where name=’prasad’ ;
This statement replaces (updates) the salary to 20000.Where name is the column
name of the table emp.
4. DELETE Command:
Removing rows from the tables in SQL is easier than inserting them. To delete
rows we can use the DELETE Command. Again the Where clause is essential to
delete. If we use the delete command without the where clause, the contents of
the entire table will be deleted.
Syntax:
delete from <table_name> where <logical_expression>;
To delete the particular row or record we should specify the condition in where
clause.
Ex: delete from emp where age=22;
All the row details of age will be deleted from the table emp. Where emp is the
table name & age is the field name.
**********************************************************************************
************
Miscellaneous Commands:--
1. COPY Command:--
It is used to copy from columns of one table to columns of another table in SQL.
<SQL by Prasad>
10. 10 STRUCTURED QUERY LANGUAGE (SQL)
Syntax:
Create table <new_table_name> as select column_name from
<existing_table_name>;
Ex: create table empl as select dept from emplo;
2. LOGICAL OPERATORS:--
a) AND Operator: AND operator is used to select the fields with Where clause for
condition testing in SQL
results only all the condition satisfies.
Ex: select dob,emp_id from emp where name=’prasad’ and salary=15000;
b) OR Operator: OR operator is used to select the fields with Where clause for
condition testing in SQL results if either of the conditions satisfies.
Ex: select * from emp where emp_id=123 or name=’prasad’;
c )NOT Operator: NOT operator is used to select the fields with Where clause for
condition testing in SQL.
Ex: select name from emp where not salary=15000;
3. CHARACTORS FUNCTIONS:--
a) Initcap: -- It is used to display the characters in which the first letter is in
Capital letter.
Ex: select initcap(‘prasad’) from dual;
Output:
INITCA
-------
Prasad
c) LOWER (char):-- It is used to convert all capital lettered characters into small
lettered characters in an SQL;
Ex: select lower(‘PRASAD’) from dual;
Output:
LOWER(
------
prasad
c) UPPER(char):-- It is used to convert all small lettered characters into capital
lettered characters in an SQL;
<SQL by Prasad>
11. 11 STRUCTURED QUERY LANGUAGE (SQL)
Ex: select upper('prasad') from dual;
Output: UPPER(
------
PRASAD
d) LTRIM(char,set):--
Ex: select ltrim('xyz abc','xyz') from dual;
Output:
LTRI
----
abc
e) RTRIM(char,set):--
Ex: select rtrim('xyz abc','abc') from dual;
Output:
RTRI
----
xyz
f) TRANSLATE(char,from to)_:-- This command is used to change the particular
character into another character. In other words it replaces a old character to
a new character.
Ex: select translate('JACK','J','B') from dual;
Output:
TRAN
----
BACK
From the above example the character ‘J’ is replaced by new character ‘B’ in the
output.
g) LENGTH Command:--
LENGTH Command is used to find the length of the given string in SQL.
Ex: select length(‘prasad’) from dual;
Output:
LENGTH('PRASAD')
<SQL by Prasad>
12. 12 STRUCTURED QUERY LANGUAGE (SQL)
----------------
6
g) LIKE Command:-- This command is used to select the particular characters
from the rows in SQL.
Ex: select * from emplo;
EMP_N NAME DEPT AGE SALARY
----- -------------------- -------------------- --------- ---------
101 Sathish.H HOD of CS 48 27000
102 Prasad.babu HRD 25 25000
99 Basavaraj Finance 24 19000
110 Manoj.Kumar Marketing 22 24999
234 Salim.Jafer Mess 23 21000
123 kenchanagouda Mess 23 21999
6 rows selected.
select * from emplo where dept like '%ss';
EMP_N NAME DEPT AGE SALARY
----- -------------------- -------------------- --------- ---------
234 Salim.Jafer Mess 23 21000
123 kenchanagouda Mess 23 21999
---: SET Operators: ---
There are situations when we need to combine the results from two or more select
statements. SQL enables us to handle these requirements by using SET operations.
The result of each select statement can be treated as SET & SQL set operations can
be applied on those sets to arrive at a final result. SQL supports the following SET
operations.
(1) UNION (2) UNION ALL (3) INTERSECT (4) MINUS
SQL statements containing these set operations are called COMPOUND QUARIES.
Two selects can be combined into a compound query by a set operation only of they
satisfies the following conditions: ---
1) The result Set of both the queries must have the same number of columns.
<SQL by Prasad>
13. 13 STRUCTURED QUERY LANGUAGE (SQL)
2) The datatype of each column in the second result set must match the datatype of
its corresponding column in the first result set.
These conditions are also referred to as “union compatibility” conditions. The
general syntax of query involving set operation is: --
<compound query> {union/union all/intersect/except} <compound query>;
To explain the above example we can consider the following query.
1) select customer_name from depositor;
It displays the set of all customers who have an account at the bank. Where
depositor is table name & customer_name is column name.
Output:
CUSTOMER_NAME
---------------------
Ashok Mehra
Ajay Mehra depositor table
Prem Desai
Rohit Roy
Nalini Deewan
2) select customer_name from borrower;
It displays the set of all customers who have loan at the bank. Where borrower is
table name & customer_name is column name.
Output:
CUSTOMER_NAME
--------------------
Manish Patel
Prem Desai borrower table
Nitish Kanna
Ashok Mehra
Kiran Dixit
************************************************************************************
**********
1) UNION OPERATION:
The union operation combines the results of two select statements into one result se
& them eliminates any duplicate rows from the result set.
Syntax:
(select customer_name from depositor) union (select customer_name from
borrower);
<SQL by Prasad>
14. 14 STRUCTURED QUERY LANGUAGE (SQL)
The OUTPUT is: ---
CUSTOMER_NAME
-------------------------
Ashok Mehra
Ajay Mehra
Prem Desai
Rohit Roy
Nalini Deewan
Manish Patel
Nitish Kanna
Kiran Dixit
It displayed the names of all the customers from both queries eliminating duplicate
rows such as Ashok Mehra from both the queries.
2) UNION ALL OPERATION:
The union all operator returns all the rows selected by either query including
duplicates.
Syntax:
(select customer_name from depositor) union all (select customer_name from
borrower);
The OUTPUT is: ---
CUSTOMER_NAME
-------------------------
Ashok Mehra
Ajay Mehra
Prem Desai
Rohit Roy
Nalini Deewan
Manish Patel
Prem Desai
Nitish Kanna
Ashok Mehra
Kiran Dixit
3) INTERSECT OPERATION:
INTERSECT operator returns only rows that are common to both the queries.
Syntax:
<SQL by Prasad>
15. 15 STRUCTURED QUERY LANGUAGE (SQL)
(select customer_name from depositor) intersect (select customer_name from
borrower);
It displays the customer_names which are present in both the queries or tables.
Output:--
CUSTOMER_NAME
-----------------------------
Ashok Mehra
Prem Desai
By default intersect eliminates the duplicates. If we want to retain (display)
duplicates we can use ‘intersect all’ instead of intersect.
4) MINUS (EXCEPT) OPERATION:
Except returns the rows from the first query that were not present in the record.
Syntax:
(select customer_name from depositor) minus (select customer_name from
borrower);
It displays all the names of customers from the depositors table but not from the
borrower table.
Output:
CUSTOMER_NAME
----------------------------
Ajay Mehra
Rohit Roy
Nalini Deewan
By default minus eliminates the duplicates. If we want to retain duplicates we can
use ‘minus all’ instead of ‘minus’.
************************************************************************************
**********
SORTING (Order by Clause):
The order by clause gives us a way of ordering the results. The data is ordered in the
way we want it, not the way in which it was entered. The order by clause tells SQL
that we want the specified fields displayed in acending or descending order.
Consider the table loan below,
BRANCH_NAME AMOUNT
----------------------- -------------
Abids 7895
Ameerpet 127
<SQL by Prasad>
16. 16 STRUCTURED QUERY LANGUAGE (SQL)
Ameerpet 2810
Koti 432
Punjagutta 1234
The above rows are obtained by following query,
Select branch_name,amount from loan order by branch_name;
We can observe the values of the rows which are displayed in ascending order
because by order by clause. We have given the column branch_name & by default
order by clause sorts the values in ascending order. For ascending order we may
specify as ‘asc’ & fro descending order we may specify as ‘desc’ after column name.
For example;
Select branch_name,amount from loan order by branch_name desc;
Output:
BRANCH_NAME AMOUNT
----------------------- --------------
Punjagutta 1234
Koti 432
Ameerpet 2810
Ameerpet 127
Abids 7895
When ordering the data, we can have multiple sort levels
Select field_name1,field_name2,field_name3……… order by
field_name1<desc/asc> , field_name 2<desc/asc>, field_name
3<desc/asc>………….;
Explanation:
By default order by clause orders specified fields in ascending order.
Typing ‘desc’ after the field name in the order by clause tell SQL that we want
data in the specified field displayed in descending order ( Z to A & 100 to 1)
The first field name is the primary sort order, the second field name is
secondary sort order and so on………
Ex:
BRANCH_NAME AMOUNT
----------------------- -------------
Abids 7895
Ameerpet 2810
<SQL by Prasad>
17. 17 STRUCTURED QUERY LANGUAGE (SQL)
Ameerpet 127
Koti 432
Punjagutta 1234
*******************************************************************************
***************
BUILT IN FUNCTIONS (AGGRIGATE FUNCTIONS):
These functions are also referred to as group functions. They returns a value based
on the values in the column. Aggregate functions perform functions like calculations
on a set of values & returns a single value. Aggregate functions are often with the
group clause of the select statement. All aggregate functions are determinates ,they
returns the same value anytime they called with a given set of input values.
The select list of a select statement (either a sub query or a parent query)
A having clause.
The distance between aggregate functions & normal functions is that aggregate
functions use entire column of data as their input & produce a single output the
‘normal’ operate on each element in the column of data.
1) SUM: It returns the sum of all values or only distinct values in the expression sum
can be used with numeric values only. NULL values are ignored. It returns the sum
of unique values.
Ex: select sum(amount) from loan;
Output:
SUM(AM
------------
12498
2) AVERAGE: The avg function computes the average of a column, NULL values are
ignored. To find the average of a amount in loan table the query will be
Ex: select avg(amount) from loan;
Output:
AVG(AM
----------
2499.6
<SQL by Prasad>
18. 18 STRUCTURED QUERY LANGUAGE (SQL)
3) MAX: It returns the maximum value in the expression. If we want to find the
largest value in a column, we use max function. To find the maximum amount in the
loan relation (table) the query will be as follows,
Ex: select max(amount) from loan;
Output:
MAX(AM
----------
7895
4) MIN: It returns the minimum value in the expression. To find the minimum
amount in the loan relation (table)
the query will be as follows,
Ex: select min(amount) from loan;
Output:
MIN(AM
----------
127
5) COUNT: The function count returns the numbers of rows in a table. To find the
number of rows in the loan relation (table) the query will be as follows,
Ex: select count (*) from loan;
Output:
COUNT(*)
---------
5
*******************************************************************************
***************
JOINS (Multi table queries):
The process of forming rows from two or more tables by comparing the contents of
related columns are called joining tables. The resulting table is called a join between
the tables. The different types of joins that can be made between tables are as
follows.
1) Simple join
a) Equi join
b) non-eque join
2) Self join
3) Outer join.
<SQL by Prasad>
19. 19 STRUCTURED QUERY LANGUAGE (SQL)
Joins are foundation of multi-table query processing in SQL.
a) Equi joins: A join based on an exact match between two columns is called equi
joins. This is because the comparison operator in the join condition is ‘=’ (equal).
b) Non-equi joins: A non eque joins specify the relationship between columns
belonging to different tables by making use of the relational operators (>, <, >=, <=,
<>).
2) Self joins: Joining of table itself is known as self join. In other words it joins one
row in table to another. It can compare each rows of the table to itself & also with
the rows of the same table.
3) Outer joins: The outer joins extends the result of simple join. An outer join
returns all the rows returned by simple join as well as those rows from one table
that do not match any row from the other table. The symbol ‘+’ represent the outer
join.
************************************************************************************
**********
TABLE ALIASES
To prevent the ambiguity in a query we include table in the select statement. Table
aliases are used to make a multiple table queries shorter & more readable. As a
result , we give an alias to the table in the ‘from’ clause.
The alias can be used instead of table name throughout the query.
For example,
Select e.dept_no, e.ename,d.dept_no,d.dname from emp e, dept.d where
e.dept_no=d.dept_no;
The above example refers to the table alias, where ‘e’ refer to the table emp
&‘d’ refer to the table dept.
The aliases which are defined in the ‘from’ clause are separate from the table name
by space.
************************************************************************************
**********
INDEXES
An Index is an ordered list of contents of a column or group of columns in a table. An
index created on a single column of the table is called simple index. When multiple
table columns are included in the index is called composite index.
Creating the Index for a table:
<SQL by Prasad>
20. 20 STRUCTURED QUERY LANGUAGE (SQL)
Simple Index: CREATE INDEX index_file_name ON table_name(column_name);
Ex; create index client_ndx on client_master(client_no);
Composite Index: CREATE INDEX index_file_name ON
table_name(column_name1,column_name2….n);
Ex: Create a composite index on the sales_order_details table for the columns
s_order_no and product_no.
Create index sales_order_details_ntx on
sales_order_details(s_order_no,product_no);
The index in the above examples do not enforce uniqueness i.e. the column included
in the index can have duplicate values. To create a unique index, the keyword
UNIQUE should be included in the create index command.
Syntax: CREATE UNIQUE INDEX index_file_name ON table_name
(column_name);
For example; create a unique index on table client_master, with the field client_no.
SQL> CREATE UNIQUE INDEX client_ndx ON client_master(client_no);
When the user defines a primary key or a unique key constraint, Oracle
automatically creates a unique indexes on the primary key column or unique key.
Dropping Indexes: An Index can be dropped by the DROP Command.
Syntax: DROP INDEX <index_file_name>;
Ex: Drop index client_ndx on table client_master can be dropped by the following
query.
SQL> DROP INDEX client_no;
When the user drops the primary key, unique key constraints or the table, Oracle
automatically drops the indexes on the primary key column, unique key or table
itself.
************************************************************************************
**********
<SQL by Prasad>