SQL: Structured Query Language It enables to create and operate on relational databases, which are...

39

description

Processing Capabilities of SQL  Data Definition Language (DDL)  Interactive Data Manipulation Language (DML)  Embedded Data Manipulation Language  View Definition  Authorization  Integrity  Transaction Control

Transcript of SQL: Structured Query Language It enables to create and operate on relational databases, which are...

SQL: Structured Query Language

It enables to create and operate on relational databases, which are sets of related information stored in tables.

It is a standard language for communicating with the RDBMS from any tool.

Processing Capabilities of SQL

Data Definition Language (DDL) Interactive Data Manipulation Language (DML) Embedded Data Manipulation Language View Definition Authorization Integrity Transaction Control

DATA DEFINITION LANGUAGE

The SQL DDL Provide commands for

Defining Relations (Create Table)

Deleting Relations (Delete Table)

Creating Indexes (Create index)

Modifying Relations (Alter Table)

DATA MANIPULATION LANGUAGE

DML includes query language based on both the relational algebra and the tuple relation calculus. It includes commands to

INSERT (Insert into <Tablename>)

DELETE (Delete from <tablename>)

MODIFY (Update <tablename> )

SQL Data Types:-

Char(n)/ varchar2(n)- to hold character string

Number(n, d)- to hold data of type number

n- maximum number of digits d- number of digits to right of decimal

point Date- to hold data of type date

Long- to hold character of up to 65,535 characters

Raw- to hold data of byte oriented such as graphics

Long raw- similar as Raw but stores 2 Gb

Create table Command-Create table <table-name>(<column-name> <data type>

[(<size>)],<column-name> <data type>

[(<size>)….]);

Eg: To create table Employee with following scheme.

Employee(ecode, ename, sex, grade, gross)

Create table Employee(ecode number, ename char(20), Sex char(1), grade char(2), gross number(7,2));

Constraint:-A constraint is a condition or check

applicable on a field or set of fields.

When a table is created, constraints are placed on the fields to check the entered values.

Different Constraints:

Unique constraint Primary key constraint Default constraint Check constraint

Unique ConstraintThis constraint ensures no two rows have same

value in the specified columnsEg. Create table employee( ecode number NOT NULL UNIQUE,Ename char (20) NOT NULL,Sex char(1) NOT NULL,Grade char(2),Gross number(9,2));

UNIQUE Constraint applied on ecode of employee table ensures that no two rows have same ecode value.

Primary Key constraint:Similar to Unique constraint except that only one

column or one group of columns can be applied in this constraint. The Primary Key cannot allow NULL values.

Eg. Create table employee( ecode number NOT NULL Primary Key,Ename char (20) NOT NULL,Sex char(1) NOT NULL,Grade char(2),Gross number(9,2));

Default Constraint:This constraint inserts default value for the

column if the user does not enter a value for the column.

Eg. Create table employee( ecode number NOT NULL Primary Key,Ename char (20) NOT NULL,Sex char(1) NOT NULL,Grade char(2) Default ‘E1’,Gross number(9,2));

According to above command if no value is provided for grade, the default value of ‘E1’ will be entered.

Check Constraint:This constraint limits values that can be

inserted into a column of a table.Eg. Create table employee( ecode number NOT NULL Primary Key,Ename char (20) NOT NULL,Sex char(1) NOT NULL,Grade char(2) Default ‘E1’,Gross number(9,2) check (gross>2000);

This ensures value inserted for gross must be greater than 2000

Check constraint involving more than one column:

Eg. Create table items(icode char(5),Descp char(20),ROL number(5),QOH number(3),Check (ROL< QOH));Here check constraint was referring to more than one

columns, hence it has been in the end of table definition, after all the column definitions

Check constraint can consist of: A list of constant expressions specified using

INEg. Decp char(20) CHECK (decp IN (‘NUT’,

‘BOLT’, ‘SCREW’, ‘WRENCH’, ‘NAIL’)) Range of constant expressions using

BETWEENEg. Prince number(9,2) CHECK(Price BETWEEN

253.00 and 770.00) A pattern specified using LIKEEg. Ordate char(10) NOT NULL CHECK (ordate LIKE ‘--/--/----’) Multiple conditions using OR, AND etc.Eg. CHECK (discount = 0.15 AND City=

‘HISSAR’) OR ( discount = 0.13 AND city = ‘JAIPUR’)

OR ( discount = 0.17 AND city =

‘MOHALI’))

SELECT COMMAND: SELECT command make queries on the

database. A QUERY is a command that is given to produce certain specified information from the database tables

SELECT <column name> [, <column name>,….]

From <table name>;Eg. (1) SELECT empno, ename from emp; (2) SELECT * from emp; (to view all

column in emp table)

DISTINCT keyword: DISTINCT keyword eliminates duplicates

rows from the results of a SELECT statement

Eg. Select DISTINCT city from Suppliers;In the output there would be no duplicate

rows. ALL keyword:• ALL keyword includes all the rows without considering the duplicate entries

• Eg. Select ALL city from Suppliers;

Selecting specific Rows- WHERE clause

Eg. Select empname, sal from emp where sal > 2900;

This clause will extract only those rows where sal is having value more than 2900.Relational Operators-• To compare two values, a relational operator is used. The result of the comparison is true or false. Relational Operators recognized by SQL:

• =, >, <, <=, >=, <>(not equal to)

Eg. Select * from suppliers where city<> ‘DELHI’;

Above query will not display those suppliers details whose city column value is DELHI.

Select empname from emp where deptno<>20;

Above query will not display those employee names whose dept number is 20

Logical Operators- (OR, AND, NOT)

1) To list the employee details having grades E2 or E3.

Select ecode, ename, grade, gross from employee where (grade=‘E2’ OR grade=‘E3’);

2) To list all the employees’ details having grades as ‘E4’ but with gross < 9000.

Select ecode, ename, grade, gross from employee where (grade=‘E4’ and gross< 9000);

3) To list all the employees’ details whose grades are other than ‘G1’

Select ecode, ename, grade, gross from employee where (NOT grade= ‘G1’);

Condition based on a range- BETWEEN

Select icode, descp, QOH From items WHERE QOH BETWEEN 30 and 50;

Above query will display only those items whose QOH falls between 30 to 50.

Select empno, ename, dept from emp where sal between 2500 and 5000.

Above query will display only those employees’ whose salary falls in between 2500 and 5000.

Select empno, ename, dept from emp where sal Not Between 2500 and 5000.

Above query will not display those employee whose salary is not between 2500 and 5000.

Condition based on LIST- IN / NOT IN

Select * from members where city IN(‘DELHI’, ‘CHENNAI’, MUMBAI’);

Above query will display the list of members from DELHI, CHENNAI, MUMBAI cities.

Select * from members where city NOT IN(‘DELHI’, ‘CHENNAI’, MUMBAI’);

Above query will display the list of members from who are not from cities DELHI, CHENNAI, MUMBAI

Condition Based on Pattern Matches- (‘%’, ‘_’)

SQL includes a string-matching operator- (1) percent (%)- The % character matches

any substring(2) Underscore (_) - The _ character

matches any character.Patterns are case sensitiveEg. (1) To list members which are in area

with pincode starting with 13.Select firstname, lastname, city from

members where pin LIKE ’13%’;

2) To list employees who have four letters with names ending with ‘D’

Select empno, ename from emp where ename LiKE ‘---D’;

3) To list employees whose name starts with ‘S’

Select empno, ename from emp where ename LIKE ‘S%’;

4) To list employees whose name’s second character is ‘J’

Select empno, ename from emp where ename LIKE ‘_J%’

Searching for NULL- The NULL value in a column can be

searched for in a table using IS NULL in the where clause.

Select empno, ename, job from emp where Deptno IS NULL;

(NULL- columns not having value is considered as NULL)

Sorting Results- ORDER BY clause

Results of SQL query can be sorted in a specific order using ORDER BY clause

The ORDER BY clause allows sorting of query results by one or more columns

The sorting can be done either in ascending or descending order

Eg. Select * from emp order by ename;Above query arranges the records in

alphabetical order of ename value.By default order by clause arranges in

ascending order.

To display records in descending orderSelect * from emp order by ename desc;Above query gives output in descending

order of ename

Select * from employee ORDER BY grade DESC, ename ASC;

Above query displays records first in the descending order of grade and within the same grade employees are displayed in the ascending order of Ename

Performing Calculations- Using SELECT clause calculations can be

performed. For this Oracle provides a dummy table called DUAL. SELECT clause always works with a table.

DUAL table is a small worktable, which has just one row and one column.

Select 4*3 from Dual;Output: - 12Select sysdate from dual;Output:- 06-Jun-08 (Displays current system date)

AGGREGATE FUNCTIONS:- SQL’s aggregate functions:

Avg – to compute average value Min – to find minimum value Max – to find maximum value Sum – to find total value Count – to count non-null values in a column Count( *) – to count total number of rows in a

tableSelect avg(sal) from emp;Select min(sal) from emp where deptno= 10;Select count(*) from emp where sal> 3000;Select count (ALL CITY) from members;Select count (DISTINCT CITY) from members;

Grouping Result- GROUP BY Clause GROUP BY Clause is used in SELECT

statements to divide the table into groups.

To calculate the number of employees in each grade and average gross for each grade of employees

SELECT job, count(*), sum(comm) from emp group by job;

Placing conditions on Groups- HAVING Clause The HAVING clause places conditions on

groups in contrast to WHERE clause that places conditions on individual rows.

WHERE conditions cannot include aggregate functions, HAVING conditions can do so.

SELECT avg(gross), sum(gross) from employee GROUP BY grade HAVING grade= ‘E4’;

INSERT Command:- INSERT INTO <tablename> [<column list>]

VALUES (<value>, <value>…);

Eg. INSERT INTO employee VALUES (1001, ’Ravi’, ’M’, ’E4’, 4670.00);

INSERT INTO employee (ecode, ename, sex, grade, gross) VALUES (1001, ’Ravi’, ’M’, ’E4’, 4670.00);

INSERT INTO employee (ecode, ename, sex) VALUES (2014, ’Manju’, ’F’);

DELETE Command:- DELETE Command removes rows from a table.

DELETE FROM <tablename> [WHERE <predicate>];

Eg. To remove all the contents of items tableDELETE From items;

To remove the tuples from employee that have gross less than 2200.00

DELETE From employee WHERE gross<2200.00;

UPDATE Command:- Update Command allows to change some

or all the values in an existing rows. Update command specifies the rows to

be changed using the WHERE clause and the new data using the SET keyword

Eg. UPDATE items SET ROL= 250; UPDATE items SET ROL=400, QOH=700

WHERE icode < ‘I040’; UPDATE employees SET grade=NULL

WHERE grade= ‘E4’;

VIEW:- VIEW is a virtual table with no data, but

can be operated like any other table. It is like a window through which we can

view the data of another table, which is called base table.

Using view we can query, update (if allowed), inserted (if allowed), deleted from (if allowed) etc.

The SELECT statement used in a view definition cannot include: ORDER BY clause INTO clause

CREATE VIEW- CREATE VIEW taxpayee AS SELECT *

FROM employee WHERE gross > 8000;This view will be having details of those

employees that have gross more than Rs. 8000/-.

ALTER TABLE- ALTER TABLE command is used to

change the definitions of existing table. It can be used to add new columns or

modify the existing columns of table. ALTER TABLE <tablename> ADD

<columnname> <data type> <size>; ALTER TABLE <tablename> MODIFY

(columnname newdatatype (newsize)); Eg. Alter table Emp Add (tel_number

integer); ALTER TABLE Emp MODIFY (Job

char(30));

DROP TABLE & DROP VIEW

DROP TABLE allows to drop table from database. A table with rows in it cannot be dropped. To remove all the rows use DELETE command.

Once the DROP command is issued table will no longer be recognized

To delete a view DROP VIEW command is used. When a view is dropped, it does not cause any change in its base table.

Eg. DROP TABLE EMP; DROP VIEW TAXPAYEE;