IV SQL
IV SQL
Introduction to SQL:
SQL was invented and developed by IBM in early 1970’s. SQL stands for
structured query language.
IBM was able to demonstrate SQL which could be used to control relational
database. The SQL implemented by ORACLE CORPORATION is 100%
compliant with the ANSI / ISO standard SQL data language.
Oracle database language is SQL, which is used for storing and retrieving
information in oracle.
A table is a primary database object of SQL which is used to store data.
A table hold data in the form of rows and columns to communicate with the
database.
Table Definition:
A Table is a unit of storage which holds data in the form of rows and
columns. The Data definition language used for table definition can be classified into the
following for categories.
Create
Alter
Drop
Truncate
1
Create Table:
Create command is used to create the new table.
Syntax;
Create table <table name> (column1 data type, column2 data type…….)
Example:
Create table customer(custid number(5), Name varchar(20), address varchar(20));
Example:
Following is an example, which creates a CUSTOMERS table with ID as primary key and NOT NULL are
the constraints showing that these fields can not be NULL while creating records in this table:
SQL> CREATE TABLE CUSTOMERS(
ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
You can verify if your table has been created successfully by looking at the message displayed by
the SQL server, otherwise you can use DESC command as follows:
SQL> DESC CUSTOMERS;
+---------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------------+------+-----+---------+-------+
| ID | int(11) | NO | PRI | | |
| NAME | varchar(20) | NO | | | |
| AGE | int(11) | NO | | | |
| ADDRESS | char(25) | YES | | NULL | |
| SALARY | decimal(18,2) | YES | | NULL | |
+---------+---------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
The NOT NULL constraint enforces a field to always contain a value. This means that you
cannot insert a new record, or update a record without adding a value to this field.
The table name in the above example should adhere strictly to the following norms.
Alter table:
The Alter table command used to create the need of the following situations.
Example:
Table created.
Table altered.
Table altered.
Drop table:
Drop command is used to drop the table from the database.
Syntax:
Drop table <table name>;
Example:
Drop table customer;
Truncate table:
Truncate table is used to delete all the rows associated with the table.
Syntax:
Truncate table <table name>;
Example:
Truncate table customer;
1. Insert
2. Select
3. Update
4. Delete
Insert command:
The Insert command is used to add me or more rows to a table. While using this
command the values are separated by common and the data type char and date are
enclosed in apostrophes.
The values must be entered in the some order as they are defined in the table.
Syntax:
Insert into <table name> values( a list of values);
Example:
Insert into order values(12, ’12-jan-74’ , 3, null);
The following example illustrates the concept of inserting more then the record using a
single insert command.
Example:
Insert into order into values(&no, ’&ord_date’ , ’&comm’, total);
4
Insert into order_into values(‘14/12/88 9:30’ ‘dd/mm/yy 44:mi’);
Example:
Table created.
1 row created.
1 row created.
1 row created.
Select command:
Select command is used to retrieve the data from the table.
Syntax:
Select column_name…… from table name…;
Example:
The following example shows how to retrieve the all the information from a table
5
The following example shows how to select specific fields from a table
PRONAME
---------------
soap
shampoo
toothpaste
PROID
----------
101
102
103
;
Selecting distinct rows:
Distinct clause is used to prevent the selection of duplicate rows.
Example:
Select distinct repid from customer;
Where clause:
Where clause is used to select specific row from a table. It can appear
only the from clause,
Example:
PRICE QUANTITY
---------- ----------
30 300
50 200
Order by clause:
It is used to arrange rows in descending or ascending order.
Example:
PROID PRONAME
6
---------- ---------------
101 soap
102 shampoo
103 toothpaste
104 soap
106 jam
PROID PRONAME
---------- ---------------
106 jam
104 soap
103 toothpaste
102 shampoo
101 soap
Example:
Create table cust as select * from customer;
Update Command:
Update command is used to alter the column values in a table. The update
command consist of a ‘set’ clause and an optional ‘where’ clause.
Syntax:
Update <table name> set field=value… where condition;
Table altered.
1 row updated.
1 row updated.
7
SQL> update list set price=20 where proid=103;
1 row updated.
1 row updated.
Update list
Set quantity= quantity+100
Where quantity < 500
Update list
Set quantity= (select max(quantity)
From list
Where quanity<500
Delete command:
Delete command is used to delete the specific record from the table.
Syntax:
Delete from <table name> where condition;
Example:
Delete from customer where custid=105;
Note:
It we want to delete several rows from a table, select the rows with appropriate
conditions in a ‘where’ clause.
The SQL AND and OR operators are used to combine multiple conditions to narrow data in an SQL statement. These two
operators are called conjunctive operators.
These operators provide a means to make multiple comparisons with different operators in the same SQL statement.
8
The AND Operator:
The AND operator allows the existence of multiple conditions in an SQL statement's WHERE clause.
Syntax:
The basic syntax of AND operator with WHERE clause is as follows:
You can combine N number of conditions using AND operator. For an action to be taken by the SQL statement, whether it
be a transaction or query, all conditions separated by the AND must be TRUE.
Example:
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | 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 |
+----+----------+-----+-----------+----------+
Following is an example, which would fetch ID, Name and Salary fields from the CUSTOMERS table where salary is
greater than 2000 AND age is less tan 25 years:
+----+-------+----------+
| ID | NAME | SALARY |
+----+-------+----------+
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+-------+----------+
The OR Operator:
The OR operator is used to combine multiple conditions in an SQL statement's WHERE clause.
Syntax:
The basic syntax of OR operator with WHERE clause is as follows:
You can combine N number of conditions using OR operator. For an action to be taken by the SQL statement, whether it
be a transaction or query, only any ONE of the conditions separated by the OR must be TRUE.
9
Example:
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | 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 |
+----+----------+-----+-----------+----------+
Following is an example, which would fetch ID, Name and Salary fields from the CUSTOMERS table where salary is
greater than 2000 OR age is less tan 25 years:
+----+----------+----------+
| ID | NAME | SALARY |
+----+----------+----------+
| 3 | kaushik | 2000.00 |
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+----+----------+----------+
1. Commit
2. Roll back
3. Save point
Commit:
Example:
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | 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 |
10
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is the example which would delete records from the table having age = 25 and then COMMIT the
changes in the database.
As a result, two rows from the table would be deleted and SELECT statement would produce the following
result:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Syntax:
Commit work; (or) Commit;
Roll back:
A roll back command is used to undo the word done in the current transaction.
Example:
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | 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 |
+----+----------+-----+-----------+----------+
Following is the example, which would delete records from the table having age = 25 and then ROLLBACK
the changes in the database.
11
As a result, delete operation would not impact the table and SELECT statement would produce the following
result:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | 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 |
+----+----------+-----+-----------+----------+
- We can either roll back the entire transaction so that all charges made by SQL
statement are undone.
- Roll back a transaction to a save point so that the SQL statement after the save
point are rolled back.
Syntax: Rollback
SQL> DELETE FROM CUSTOMERS
WHERE AGE = 25;
SQL> ROLLBACK;
Save point:
SAVEPOINT SAVEPOINT_NAME;
This command serves only in the creation of a SAVEPOINT among transactional statements. The
ROLLBACK command is used to undo a group of transactions.
ROLLBACK TO SAVEPOINT_NAME;
Following is an example where you plan to delete the three different records from the CUSTOMERS table.
You want to create a SAVEPOINT before each delete, so that you can ROLLBACK to any SAVEPOINT at
any time to return the appropriate data to its original state:
Integrity Constraints:
It is used to prevent invalid data entry into the table. It is nothing but
enforcing rule for the columns in a table.
1. Domain
12
2. Entity
3. Referential
Maintains the value according to the specification like ‘not null’ and ‘check’.
Not null.
Check.
Example:
Create table cust(custied number(6) not null,…);
Check constraints:
These are rule governed by logical expressions or Boolean expression.
Check conditions cannot contain sub queries.
Example:
Create table parts( price number(4) check (price >= 0.0);
Unique.
Primary Key.
Unique constraints:
13
It is used to prevent the duplication of values within the rows of a
specified column or a set of column in a table. It unique key constraints is defined in
more than one column (i,e) combination of columns, it is said to be composite unique
key. Maximum combination of columns that a composite unique key can contain is 16.
Example:
Example:
Create table customer (custid number(10) primary key,…);
Foreign Key:
A column or combination of columns included in the definition of referential
integrity which would refer to a referenced key.
Referenced Key:
It is a unique or primary key which is defined on a column belong to the parent
table.
Child table:
This table depends upon the values present in the referenced key of the parent
table, which is referred by a foreign key.
Parent table:
This table determines whether insertion or updation of data can be done in child
table. This table would referred by child’s T\table foreign key.
Example:
Parent table:
Create table bank(acc no number(10) primary key……);
Child table:
Create table Account(acc_no number(10) references bank(acc_no) on delete cascade…..);
14
On delete cascade clause:
If all the rows under the referenced key column in a parent table are deleted, then
all rows in the child table with depend foreign key column will also be deleted
automatically.
Sub Queries
SQL Subquery
Subquery or Inner query or Nested query is a query in a query. A subquery is usually added in the WHERE
Clause of the sql statement. Most of the time, a subquery is used when you know how to search for a value
using a SELECT statement, but do not know the exact value in the database. Subqueries are an alternate
way of returning data from multiple tables. Subqueries can be used with the following sql statements along
with the comparision operators like =, <, >, >=, <= etc.
SELECT
INSERT
UPDATE
DELETE
Subquery Example:
1) Usually, a subquery should return only one record, but sometimes it can also return multiple records
when used with operators like IN, NOT IN in the where clause. The query would be like,
but, if you do not know their names, then to get their id's you need to write the query in this manner,
15
SELECT id, first_name
FROM student_details
WHERE first_name IN (SELECT first_name
FROM student_details
WHERE subject= 'Science');
Output:
Id first_name
-------- -------------
100 Rahul
102 Stephen
In the above sql statement, first the inner query is processed first and then the outer query is processed.
SQL COUNT (): This function returns the number of rows in the table that satisfies the
condition specified in the WHERE condition. If the WHERE condition is not specified, then the
query returns the total number of rows in the table.
For Example: If you want the number of employees in a particular department, the query
would be:
SELECT COUNT (*) FROM employee
WHERE dept = 'Electronics';
If you want the total number of employees in all the department, the query would take the
form:
To get the count of employees with unique name, the query would be:
SQL MAX(): This function is used to get the maximum value from a column.
To get the maximum salary drawn by an employee, the query would be:
16
SELECT MAX (salary) FROM employee;
SQL MIN(): This function is used to get the minimum value from a column.
SQL AVG(): This function is used to get the average value of a numeric column.
SQL SUM(): This function is used to get the sum of a numeric column
Notice that each SELECT statement within the UNION must have the same number of columns.
The columns must also have similar data types. Also, the columns in each SELECT statement
must be in the same order.
Note: The UNION operator selects only distinct values by default. To allow duplicate values,
use the ALL keyword with UNION.
17
Moreno D.F.
2 New Orleans Cajun Delights Shelley Burke P.O. Box 78934 New Orleans 70117 USA
3 Grandma Kelly's Homestead Regina Murphy 707 Oxford Rd. Ann Arbor 48104 USA
For Example: If you want to know the total amount of salary spent on each department, the query would
be:
SELECT dept, SUM (salary)
FROM employee
GROUP BY dept;
18
SQL Views
A view is a table that derived from other views and the base tables are created using
create table staement
A VIEW is a virtual table, through which a selective portion of the data from one or more tables can be seen.
Views do not contain data of their own. They are used to restrict access to the database or to hide data
complexity. A view is stored as a SELECT statement in the database. DML operations on a view like INSERT,
UPDATE, DELETE affects the data in the original table upon which the view is based.
19