Top Banner
Structured Query Language
35

sql basics

Feb 16, 2016

Download

Documents

Ashish Palekar

The basic sql querries
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: sql basics

Structured Query Language

Page 2: sql basics

Overview of SQL It is a 4 GL Oracle9i in specific DML DDL

Page 3: sql basics

Basic SQL CommandsStatement

Description

SELECT Data retrieval statement.INSERT Data Manipulation Language (DML).

Add rows, change data, and delete few rows.

UPDATEDELETECREATE Create new tables/views, remove tables/

views, and change the schema.ALTERDROPRENAMECOMMIT Modified values of database are

permanently written into disk, rollback the changes made.

ROLLBACKSAVEPOINTGRANT Access control can be assigned or

changed.REVOKE

Page 4: sql basics

Basic data types in OracleData type DescriptionCHAR (size) Fixed length character. Max =

2000.VARCHAR2(size

Variable length character string. Max = 4000.

DATE Date. Vaild range is from Jan 1, 4712 B.C. to Dec 31, 4712 A.D.

NUMBER(size) Numbers. Max. size = 40 digits.NUMBER(size,d)

Numbers. Range = 1.0E-130 to 9.9E125.

Page 5: sql basics

EmployeeExample tables

Department

SSN Name BDate Salary

MgrSSN DNo

1111 Deepak 5-Jan-62 22000 4444 1

2222 Gopal 10-Dec-60

30000 4444 3

3333 Pooja 22-Jan-65 18000 2222 2

4444 Prasad 11-Jan-57 32000 Null 3

5555 Reena 15-Jan-85 8000 4444 3

DNo DName Loc1 Admin Chennai2 Research Bangalore3 Accounts Bangalore

Page 6: sql basics

DDL CREATE TABLE Department(

DNo number(3) not null, DName varchar2(10) not null, Loc varchar2(15),primary key (DNo));

CREATE TABLE Employee(SSN number(4) not null, Name varchar2(20) not null,BDate date,Salary number(10,2),MgrSSN number(4),DNo number(2) not null,primary key (SSN),foreign key (MgrSSN) references Employee(SSN),foreign key (DNo) references Department(DNo));

Page 7: sql basics

Data Retrieval Statement (SELECT) Syntax

SELECT *|{[DISTINCT] column | expression}FROM table(s);

The basic SELECT statement must include the following:

- A SELECT clause.- A FROM clause.

Page 8: sql basics

Example-1SELECT * FROM Employee;The * indicates that it should retrieve all the columns from Employee table. The output of this query is shown below:

Output-1 SSN NAME BDATE SALARY MGRSSN DNO ---- -------------------- --------- --------- --------- --------- 4444 Prasad 11-JAN-57 32000 3 5555 Reena 15-JAN-85 8000 4444 3 1111 Deepak 05-JAN-62 22000 4444 1 2222 Nandagopal 10-DEC-60 30000 4444 3 3333 Pooja 22-JAN-65 18000 2222 2

Page 9: sql basics

Example-2

SELECT * FROM Employee ORDER BY SSN;

Output-2 SSN NAME BDATE SALARY MGRSSN DNO----- -------------------- --------- --------- --------- --------------------------------- 1111 Deepak 05-JAN-62 22000 4444 1 2222 Nandagopal 10-DEC-60 30000 4444 3 3333 Pooja 22-JAN-65 18000 2222 2 4444 Prasad 11-JAN-57 32000 3 5555 Reena 15-JAN-85 8000 4444 3

Page 10: sql basics

Using arithmetic operatorsSELECT Name, Salary, Salary * 12FROM Employee;

Using aliasesAn alias when used for a column:Renames a column headingIt is useful in arithmetic calculations.AS keyword can optionally be used between

column name and alias name. Example-3

SELECT Name, Salary, Salary * 12 AS YRLY_SALARYFROM Employee;

ORSELECT Name, Salary, Salary * 12 "YRLY_SALARY"FROM Employee;

Page 11: sql basics

Example-4

DESCRIBE Employee;ORDESC Employee;

Output-4Name Null? Type------------------------------- -------- ----SSN NOT NULL NUMBER(4)NAME NOT NULL VARCHAR2(20)BDATE DATESALARY NUMBER(10,2)MGRSSN NUMBER(4)DNO NOT NULL NUMBER(2)

Page 12: sql basics

Select Statement with WhereExample-5

SELECT Name, SalaryFROM EmployeeWHERE Salary > 25000;

Example-6SELECT DName, LocFROM DepartmentWHERE Loc = 'Bangalore';

Example-7SELECT Name, BDateFROM EmployeeWHERE BDate = '11-Jan-57';

Page 13: sql basics

Example-8SELECT Name, BDateFROMEmployee

WHERE Salary BETWEEN 25000 AND 30000; Example-9

SELECT SSN, NameFROMEmployee

WHERE DNo IN (1, 2); Example-10

SELECT NameFROMEmployee

WHERE Name LIKE 'P%'; Example-11

SELECT Name, DNoFROMEmployee

WHERE BDate LIKE '__-JAN-__';

Page 14: sql basics

Example-12SELECT NameFROMEmployee

WHERE MgrSSN IS NULL; Example-13

SELECT Name, Salary, DNoFROMEmployee

WHERE Salary > 30000 AND DNo = 3; Example-14

SELECT Name, SalaryFROMEmployee

WHERE Name LIKE 'P%' OR Salary <= 20000; Example-15

SELECT Name, Salary, DNoFROM Employee

ORDER BY DNo DESC, Name;

Page 15: sql basics

Working with Dates

Century 19Year 99Month 07Day 23Hour 4Minute 10Second 53

SELECT SYSDATEFROM DUAL;

Page 16: sql basics

Example-16 (MONTHS_BETWEEN)SELECT MONTHS_BETWEEN(SYSDATE, '09-JAN-1983')

"Experience"FROM DUAL;

Output-16Experience---------------

247.73471 Example-17 (GREATEST & LEAST)

The function GREATEST finds the earliest date and LEAST finds the oldest date in the list.SELECT GREATEST('10-JAN-93', '10-JAN-98'),

LEAST('10-JAN-93', '10-JAN-98')FROM DUAL;

Output-17GREATEST( LEAST('10--------- ---------10-JAN-98 10-JAN-93

Page 17: sql basics

Use of TO_DATE TO_DATE function is to convert any character literal string

into a valid date format. Example-22 SELECT TO_DATE('1-Sep-2003', 'DD/MM/YYYY')

FROM DUAL; Output-22

TO_DATE('---------01-SEP-03

Example-23SELECT TO_DATE('08/30/2003', 'DD/MM/YYYY')FROM DUAL;

Output-23ERROR at line 1:ORA-01843: not a valid month

Page 18: sql basics

Character Functions Program Output

SELECT LOWER('Bangalore') FROM DUAL;

bangalore

SELECT UPPER('Bangalore') FROM DUAL;

BANGALORE 

SELECT INITCAP('bangalore institute of technology') FROM DUAL;

Bangalore Institute Of Technology 

SELECT CONCAT(‘Hello',‘Dear') FROM DUAL;

Hello Dear 

SELECT SUBSTR('Database', 5, 4) FROM DUAL;

base

SELECT LENGTH('Database') FROM DUAL;

8  

SELECT INSTR('Database', 'b')FROM DUAL;

SELECT INSTR('Database', 'x') FROM DUAL;

0  

Page 19: sql basics

April 22, 202319

SELECT LPAD(Salary, 8, '*') FROM EmployeeWHERE SSN = 1111;

***22000   

SELECT RPAD(Salary, 8, '*')FROM EmployeeWHERE SSN = 1111;

22000***  

SELECT LTRIM(' Database', ' ')FROM DUAL;

Database  

SELECT RTRIM('Database...', '.')FROM DUAL;

Database 

SELECT REPLACE('Database', 'base', 'type')FROM DUAL;

Datatype   

Page 20: sql basics

Aggregate Functions COUNT AVG MAX MIN STDDEV SUM VARIANCE

Page 21: sql basics

Example-24SELECT COUNT(*) AS "No. of Employees"FROM Employee;

Example-25SELECT SUM(Salary) AS Total FROM Employee;

Example-26SELECT Name, MAX(Salary), MIN(Salary)FROM Employee;

Page 22: sql basics

GROUP BY ClauseThe rules to be followed while using GROUP BY clause are given below:

You can't have non-group function or column in SELECT clause.

Group functions ignore nulls.By default the result of GROUP BY

clause sort the data in ascending order.

Example:SELECTDNo, SUM(Salary), COUNT(*), AVG(Salary)FROM EmployeeGROUP BY DNo;

Page 23: sql basics

Example-27SELECT DNo, SUM(Salary), COUNT(*), AVG(Salary)FROMEmployeeGROUP BY DNo, MgrSSN;

HAVING clauseSELECTDNo, AVG(Salary)FROM EmployeeGROUP BY DNoHAVING DNo = 3;

Page 24: sql basics

The order of evaluation when all the clauses are specified is given below:

1. First all rows matching the WHERE conditions are retrieved.

2. These rows are grouped using the column(s) in GROUP BY clause.

3. Finally, groups matching the HAVING clause condition are retained.SELECT DNo, AVG(Salary)FROM EmployeeWHERE BDate LIKE '__-JAN-__'GROUP BY DNoHAVING MAX(Salary) > 10000;

Page 25: sql basics

MULTITABLE QUERIES Simple Equi-Joins : guidelines

Table names in the FROM clause is separated with commas.

Use appropriate joining condition. This means that the foreign key of table1 will be made equal to the primary key of table2.

When the attributes or columns have the same names, tag them with table names using dot notation.

Without proper joining condition or attributes the SQL will display the Cartesian product of the tables in the FROM clause.

Page 26: sql basics

Example-28: Display the employee names and the department names for which they work.SELECT Name, DNameFROM Employee, DepartmentWHERE Employee.DNo = Department.DNo;

Example-29 : Display only employees working for Accounts department.SELECT Name, Salary, DNameFROM Employee, DepartmentWHERE (Employee.DNo = Department.DNo)AND (DName = 'Accounts');

Page 27: sql basics

Self-Join and Table AliasesExample-30 : Find the employee

who earns more than ‘Nandagopal’.SELECT e1.Name, e1.SalaryFROM Employee e1, Employee e2WHERE (e1.Salary > e2.Salary) AND (e2.Name = 'Nandagopal');

Page 28: sql basics

Right-Outer Join Example-31 :

SELECT Name, DNameFROMEmployee E, Department DWHERE E.Name = D.DName(+);

Output-31NAME DNAME-------------------- ----------DeepakNandagopalPoojaPrasadReena

Page 29: sql basics

Left-Outer JoinExample-32SELECT Name, DNameFROM Employee E, Department DWHERE E.Name(+) = D.DName;Output-32NAME DNAME-------------------- ---------- Accounts Admin

Research

Page 30: sql basics

NESTED QUERIES or SUB QUERIES SELECT <column(s)>FROM table WHERE <condn operator>

(SELECT <column> FROM table);

Outer query uses the result of the inner query. If the inner query returns only one row it is called

as single row sub queries. Alternatively if the inner query returns a set of

rows (more than one row) it is classified as multiple-row sub queries.

The comparison condition may be a single row operator like >, =, >=, <, <=, <>) or multiple row operators like IN, ANY, ALL.

Page 31: sql basics

Single-Row Nested Queries Display the names of the employees working for

Accounts department.SELECT NameFROM EmployeeWHERE DNo =

(SELECT DNO FROM Department WHERE DName = 'Accounts');

Display names of employees whose salary is greater than the employee SSN=1111.SELECT NameFROM EmployeeWHERE Salary >

(SELECT Salary FROM Employee WHERE Name = 1111);

Page 32: sql basics

Example-33 Display all the employees drawing more than or

equal to the average salary of department number 3.SELECT Name, SalaryFROM EmployeeWHERE Salary >=

(SELECT AVG(Salary) FROM Employee GROUP BY DNO

HAVING DNo = 3);

Page 33: sql basics

Multiple-Row Nested Queries IN: Equal to any member in the list. ANY: Compare value to each value returned by

the subquery. ALL: Compare value to all the values returned by

the subquery.

Page 34: sql basics

Display the name of the highest paid employee.SELECT Name, SalaryFROM EmployeeWHERE Salary =(SELECT MAX(Salary) FROM Employee);

SELECT Name, SalaryFROM EmployeeWHERE Salary IN(SELECT MAX(Salary) FROM Employee);

Both '=' and 'IN' works, because the inner query produces a single

tuple.

Page 35: sql basics

Find the Name and Salary of people who draw in the range Rs. 20,000 to Rs. 40,000.Select Name, Salary from Employee where Salary = (Select Salary from Employee where Salary between 20000 and 40000);

Error: ORA-01427: single-row subquery returns more than one row

Correct Query:Select Name, Salary from Employee where Salary IN(Select Salary from Employee where Salary between 20000 and 40000);