Unit III SQL (RDBMS)
Unit III SQL (RDBMS)
Data types come in several forms and sizes, allowing the programmer to create
tables suited to the scope of the project.
A table is database object that holds user data. Table is made up of rows and
columns.
The columns in the table are called as the fields and the rows in the tables are
called as the records.
Each column of the table will have a specific data type bound to it.
Introduction to SQL:
A database language allows one to create database and table
structures to perform basic data management operations and to perform
complex queries designed to transform raw data into useful information. SQL
functions categories:
SQL Commands
Rules:
Syntax:
Table Created
Example:
1 row created
Syntax:
Table altered.
Syntax:
Example:
Table altered.
Syntax:
Example:
SQL> alter table ex1
2 modify(emailid varchar(25))
3 ;
Table altered.
Renaming Tables:
The rename operation is done atomically, which means that no other thread can
access any of the tables while the rename process is running.
Syntax:
Example:
Table renamed.
Syntax:
Example:
Syntax:
Commit;
ROLLBACK:
A Rollback does exactly the opposite of Commit. It ends the transaction
but undoes any changes made during the transaction.
Syntax:
Rollback;
Grant
SQL Grant command is specifically used to provide privileges to database
objects for an user.
Syntax:
grant privilege_name on object_name to {user_name | public | role_name}
Example
grant delete, select on student to Anita
Revoke
Revoke command withdraw user privileges on database objects if any granted.
Syntax:
revoke privilege_name on object_namefrom {user_name | public | role_name}
Example
revoke delete, select on student from Anita
SELECT Command
o Once data is inserted in to the table, the next logical operation would be
to view what has been entered
o The Select sql statement is used.
o It is used to retrieve rows selected from one or more tables
Syntax:
Select * from <Table Name>;
Example:
Syntax:
Select <columnname1>, <columnname2> from <tablename>;
Example:
SQL> select shtno, name from student;
Shtno Sname
100 Anita
101 Beena
102 Divya
Syntax:
Select * from <table name> where <condition>;
Example:
SQL> select * from student where htno = 102;
Shtno Sname Semailid Scourse
102 Divya [email protected] Bsc
Syntax:
Select <columnname1>, <columnname2> from <table name>
Where <condition>;
Example:
SQL> select shtno,name from student where htno=102;
Shtno Sname
102 Divya
Operators in SQL
Symbol Meaning
= Equal to
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
<> or != Not Equal to
Arithmetic Operators:
Arithmetic Description
Operator
+ Add
- Subtract
* Multiply
/ Divide
^ Power
SQL allows one to have multiple conditions in a query through the use of
logical operators.
Special Operators
Set operators
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.
1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS
Union All is similar to Union. But it also shows the duplicate rows.
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.
SELECT * FROM t2
MINUS
SELECT * FROM t1;
The UPDATE command is used to change or modify the data values in a table.
It updates
a) All the rows from a table
b) A select set of rows from a table.
Update statement updates columns in the existing table’s rows with new values.
The SET clause indicates which column data should be modified and the new
values that they should hold.
The Where clause specifies which rows should be updated, otherwise all table
rows are updated.
Syntax:
Update <table name>
Set <column name1> = <Expression1>, <column name2> =
<Expression2>;
Example:
SQL> Update stu set scourse =’Bcom’;
Update stu set scourse =’bcom’ where shtno between 110 and 120
DELETE Operations
Example:
Delete from stu;
Delete from stu where htno=103;
Destroying Tables
Syntax:
Drop table <table name>;
Example:
Drop table student;
DISTINCT Clause:
Sql’s Distinct clause produces a list of only those values that are different
from one other.
Example:
Select distinct scourse from stu;
Scourse
Bcom
Bsc
BA
Aggregate Functions
SQL performs various mathematical functions.
COUNT
Returns the number of rows where expression is not null. Count can be
used in conjunction with the DISTINCT clause.
Syntax:
Count([<Distinct>] <expr>)
Example:
SQL> select count(htno) from student;
htno
----------------
6
Count(*) – Returns the number of rows in the table, including duplicates and
those with nulls.
Maximum
----------
106 90
Minimum
----------
100 12
SUM
The SUM function computes the total sum for any specified attribute.
Example:
SQL> select sum(marks) "TotalPay" from student;
TOTALPAY
----------
721
AVG
Returns an average value of ‘n’ ignoring null values in a column.
Example:
SQL> select avg(htno) "Average" from student;
Average
----------
103
Dual Table:
Dual table is created by oracle along with the data dictionary. It consists
of exactly one column whose name is dummy and one record of value X. It is
the pseudo table of oracle.
D
-
X
Ordering a listing
Using Order By clause
The Order By clause is especially useful when the listing order is important
Syntax:
Select <column name>, <column name> from <table name>
[where condition] [order by <column name>[Asc|Desc]];
Example:
SQL> select sno,name,price from test1
2 order by price asc;
Example:
SQL> select sno,name,price from test1
2 order by name,price;
Grouping Data
Group By Clause
Syntax:
Having Clause
The Having clause can be used in conjunction with the Group By clause.
Having imposes a condition on the group by clause, which further filters the
groups created by the Group By clause. Having clause is applied to the output
of Group By clause operation.
Example:
A single column primary key is called a Simple key. A multicolumn primary key
is called a composite key. A primary key can be defined in either a Create table
statement or an Alter table statement.
Table created.
SQL> insert into cust_mstr
2 values('c1','suresh','ravi','kumar','07-may-2009');
1 row created.
SQL> /
insert into cust_mstr
*
ERROR at line 1:
ORA-00001: unique constraint (SCOTT.SYS_C008084) violated
The table that defines the primary or unique key is referenced by the foreign key
is called Primary table or Master table.
A foreign key can be defined in either a Create table statement or an Alter table
statement.
Records cannot be inserted in to a detail table if corresponding records in the
master table do not exist
Records of the master table cannot be deleted if corresponding records in the
detail table actually exist
The default behavior of the foreign key can be changed using the ON DELETE
CASCADE option. When the On Delete Cascade option is specified in the foreign
key definition, if a record is deleted in the master table, all corresponding records
in the detail table along with the record in the master table will be deleted.
Table created.
Table dropped.
SQL> create table cust_acct
2 (
3 custacc varchar2(10) primary key,
4 caccname varchar2(10),
5 accdet varchar2(15),
6 custno varchar2(5) references cust_mstr(custno) on delete cascade
7 );
1 row created.
SQL> commit;
Commit complete.
1 row deleted.
no rows selected
Types of Join
o Inner
o Outer (Left,Right,Full)
o Cross ===== X
Consider two tables’ students and student’s course
Student Table
Inner Join
Inner Joins are also known as Equi Joins. The INNER JOIN keyword
selects all rows from both the tables as long as the condition is satisfied . In short
the Inner Join returns all rows from both tables where there is a match.
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
INNER JOIN table2
ON table1.matching_column = table2.matching_column;
Example:
SQL> SELECT StudentCourse.COURSE_ID, Student.NAME,
Student.AGE FROM Student INNER JOIN StudentCourse
ON Student.ROLL_NO = StudentCourse.ROLL_NO;
Outer Join
Outer joins are similar to inner joins, but give flexibility when selecting
data from related tables. This type of join can be used in situations where it is
desired to select all rows from the table on the left (or right, or both) regardless
of whether the other table has values and enter Null where data is missing.
Left 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 table1.column1,table1.column2,table2.column1,.... FROM table1
LEFT JOIN table2 ON table1.matching_column = table2.matching_column;
Example:
SELECT StudentCourse.COURSE_ID, Student.NAME FROM Student
LEFT JOIN StudentCourse ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Right 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 table on the
left side of join. The rows for which there is no matching row on left side, the
result-set will contain null. RIGHT JOIN is also known as RIGHT OUTER JOIN
Syntax:
SELECT table1.column1,table1.column2,table2.column1,....
FROM table1
RIGHT JOIN table2
ON table1.matching_column = table2.matching_column;
Example:
SELECT StudentCourse.COURSE_ID, Student.NAME
FROM Student
RIGHT JOIN StudentCourse
ON StudentCourse.ROLL_NO = Student.ROLL_NO;
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 table1.column1,table1.column2,table2.column1,....FROM table1
FULL JOIN table2 ON table1.matching_column = table2.matching_column;
Example
SELECT Student.NAME,StudentCourse.COURSE_ID FROM Student
FULL JOIN StudentCourse ON StudentCourse.ROLL_NO = Student.ROLL_NO;
Cross Join
A cross join returns what’s known as Cartesian product. This means that
the join combines every row from the left table with every row in the right table.
Example:
SQL> select rollno, name from student cross join student course;
Subqueries or Nested Queries
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.
• Subqueries must be enclosed within parentheses.
• A subquery can have only one column in the SELECT clause
• An ORDER BY command cannot be used in a subquery
Consider a Customer Table
ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
Example
Sql> select * from customers where Name,address in
( select ID from customers where salary >= 4500);
INDEXES
Indexes are special lookup tables that the database search engine can use to
speed up data retrieval. Simply put, an index is a pointer to data in a table. An
index in a database is very similar to an index in the back of a book.
Creating an index involves the CREATE INDEX statement, which allows you to
name the index, to specify the table and which column or columns to index, and
to indicate whether the index is in ascending or descending order.
When data is inserted in the table, the oracle engine automatically inserts the
data value in the index. For every data value held in the index the oracle engine
inserts a unique rowid value. This rowid indicates exactly where the record is
stored in the table.
Creating Simple Index
An index created on a single column of a table is called a simple index.
Syntax:
Create index <index name> on <table name> (<column name>);
Example:
SQL> create index i_empmstr on emp_mstr(fname);
Index created.
SQL> select rowid,empno,fname from emp_mstr;
Dropping Indexes
Indexes associated with the tables can be removed by using the drop index
command.
Syntax:
Drop index <index name>;
Example:
SQL> drop index i_empmstr;
Index dropped.
Views
After a table is created and populated with data, it may become necessary to
prevent all users from accessing all columns of a table, for data security reasons.
Oracle allows the creation of an object called a view.
A view is mapped, to a select sentence. The table on which the view is based is
described in the From clause of the select statement. The select clause consists
of a sub-set of the columns of the table. Thus a view which is mapped to a table
will in effect have a sub-set of the actual columns of the table.
Views can be used to insert, update and delete table data as well as view data it
is called the updateable views.
When view is used to only look at table data is called a read-only view.
Creating a View
Syntax:
Create view <view name> as
Select <column name1>,<column name2> from <table name>
Where <column name> = <expression list>
Example:
SQL> create view vw_empmstr as
2 select empno,fname,lname,desig from emp_mstr;
View created.
EMPNO FNAME
----- ----------
e5 venkat
e3 Vignesh
e1 Ramesh
Updateable Views
Views on which data manipulation can be done are called Updateable Views.
Example:
SQL> insert into vw_empmstr values('e8','Karthik','kumar','manager');
1 row created.
Dropping a View
The drop view command is used to remove a view from the database.
Syntax:
Drop view <view name>;
Example:
SQL> drop view vw_empmstr;
View dropped.
Sequences
Oracle provides an object called a sequence that can generate numeric values.
The value generated can have a maximum of 38 digits. A sequence can be
defined to:
1. Generate numbers in ascending or descending order.
2. Provide intervals between numbers
3. Caching of sequence numbers in memory to speed up their availability.
A sequence is an independent object and can be used with any table that
requires its output.
Creating Sequences
The minimum information required for generating numbers using a sequence
is:
1. The starting number
2. The maximum number that can be generated by a sequence
3. The increment value for generating the next number.
Syntax:
Create sequence <sequence name>
[increment by <integer value>
Start with <integer value>
Maxvalue <integer value>
Minvalue <integer value>
Cache <integer value>/nocache]
Create table
Create index
Create view
Create sequence ===== DDL
Increment by
Specifies the interval between sequence numbers. It can be any positive
or negative value but not zero. The default value is 1.
Minvalue
Specifies the sequence minimum value.
Maxvalue
Specifies the maximum value that a sequence can generate.
Start With
Specifies the first sequence number to be generated.
Cache
Specifies how many values of a sequence oracle pre-allocates and keeps
in memory for faster access. The minimum value for this parameter is two.
NoCache
Specifies that values of a sequence are not pre-allocated.
Example:
SQL> create sequence s_empmstr increment by 10 start with 500
2 minvalue 500 maxvalue 1000;
Sequence created.
SQL> select * from user_sequences;
sequence_name min_value max_value increment_by c o cache_size last_number
------------------------------ ---------- ---------- ------------ - - ---------- ------------------------
s_empmstr 500 1000 10 n n 20
120
Synonyms
A Synonym provides another name for database object, referred to as original
object that may exist on a local or another server. A synonym belongs to schema,
name of synonym should be unique. A synonym cannot be original object for an
additional synonym and synonym cannot refer to user-defined function.
select * from sys.synonyms ;
Synonyms are database dependent and cannot be accessed by other databases.
Syntax:
CREATE SYNONYM synonymname
FOR servername.databasename.schemaname.objectname;
GO
Schema
Database
Tables
Rows & colns
Example:
Let us assume stutable of kasturbadatabase, kgcwschema on server named
Server1. To reference this table from another server, Server2, an application would
have to use four-part named Server1.kasturba.kgcw.stutable. Also, if the location
of table were to change, for example, to another server, application would have to
be modified to reflect that change.
Now, let us create synonym for stutable table of kasturba database, kgcw schema
on server named Server1.
CREATE SYNONYM student
FOR Server1.kasturba.kgcw.stutable;
GO
Find the output in Server2 by using synonym.
SELECT ID, Name FROM stutable;