Sei sulla pagina 1di 38

Structured Query Language

Outline
SQL Ingredients

Data Types
Syntax, Key words Example queries

Database
Database is a structure that can house information about many different type of objects as well as the relationships among those objects. A tool is required to easily manipulate such information. This is called a database management system or DBMS. Most popular approach for manipulating data in a relational DBMS is SQL

Structure of the database


Organized collection of data (Tables)

Entries in the Table are single-valued


Each column in the Table should have an unique

name (called attribute name) All values in a column are values of the same attribute Each row is distinct Order of columns and rows is flexible

Terminology
Relation
Tuple Attribute

Table Row Column

File Record Field

Data Types
Integer(size), int(size), smallint(size), tinyint(size)

Holds integers only. The maximum number of digits specified in parenthesis. decimal(size,d), numeric(size,d) Holds numbers with fractions. The maximum number of digits are specified in "size". The maximum number of digits to the right of the decimal is specified in "d". CHAR(size) Holds a fixed length string (can contain letters, numbers, and special characters). The fixed size is specified in parenthesis. varchar(size) Holds a variable length string (can contain letters, numbers, and special characters). The maximum size is specified in parenthesis. DATEdate(yyyymmdd) Holds a date TIME Holds time

What is SQL ?

An ANSI standard computer language Allows you to access a database Execute queries against a database Retrieve data from a database Insert new records in a database Delete records from a database Update records in a database Querying Language for database programs like MySQL, MS SQL Server, ADQL, MS Access, DB2, Informix, Oracle, Sybase, etc. Easy

Note: Some database systems require a semicolon at the end of the SQL statement
7

Ingredients
SQL Data Manipulation Language (DML)
It includes syntax to update, insert and delete records.

SQL Data Definition Language (DDL)


It permits database tables to be created or deleted, define

indexes (keys), specify links between tables and impose constraints between database tables.

Data Manipulation Language (DML) :


SELECT - extracts data from a database table UPDATE - updates data in a database table DELETE - deletes data from a database table INSERT INTO - inserts new data into a database table

Data Definition Language (DDL) :


CREATE TABLE - creates a new database table ALTER TABLE - alters (changes) a database table DROP TABLE - deletes a database table CREATE INDEX - creates an index (search key) DROP INDEX - deletes an index WHERE impose constraints
9

Select From Where

Basic Syntax

- Attributes, column name - Table name - Restrictions, constraints

[Note: To query data on an existing database which you are not allowed to change]

For example: SALARY

Name

Rank

Amount

Years

Select name, rank, amount from salary where amount = 10000

Select * from Salary where amount > 10000

Note: SQL statements are not case sensitive.


10

Select

Alias column name alias


Select Z as Redshift or Select psfmag_u as u

Operations are permitted in select statement

Select cos(angle) from Triangles or Select (income-expenditure) as Savings

11

Select
DISTINCT Outputs only one entry/row of data for every group of rows/entries that is identical. ORDERS
OrderNumber 400 401 402 Time 1300 1310 1315 Name Mr. R. Sharma Mr. S. Pal Mr. R. Sharma Items Tomato Soup Fried rice Pasta Amoun t 45 80 75

Select DISTINCT name FROM Orders It returns the result set like : Mr.R.Sharma Mr.s.Pal

12

Where
The following operators can be used with the WHERE clause:
Operator = <> or != > < >= <= BETWEEN LIKE Description Equal Not equal Greater than Less than Greater than or equal Less than or equal Between an inclusive range Search for a pattern

13

Where
AND and OR join two or more conditions in a WHERE clause.

The AND operator displays a row if ALL conditions listed are true. The OR operator displays a row if ANY of the conditions listed are true.
For example: SALARY
Name Rank Amount Years

Select name, rank From Salary

Where amount >25000 and years > 5


Select name, rank From Salary Where amount > 25000 or years > 5
14

Where
SQL uses single quotes around text values (most database systems will also accept double quotes). Numeric values should not be enclosed in quotes.

Using Quotes

For text values:


SELECT * FROM Persons WHERE Surname=Sharma

15

Where
LIKE condition- used to specify a search for a pattern in a column. SELECT column FROM table WHERE column LIKE pattern

A "%" sign can be used to define wildcards (missing letters in the pattern) both before and after the pattern. For example: The following SQL statement will return persons with first names that start with an 'R': SELECT * FROM Persons WHERE FirstName LIKE R% The following SQL statement will return persons with first names that end with an 'a': SELECT * FROM Persons WHERE FirstName LIKE %a
16

Where
Join
Selects data from two or more tables to make the result complete or to bind data together across tables, without repeating all of the data in every table.

Tables in a database can be related to each other with keys called primary key. Each primary key value must be unique within the table. For example: SALARY
EmployeeID EmployeeID Name Amount Position Years

RANK

SELECT Salary.EmployeeID, Salary.Name, Rank.Position, Rank.Years FROM Salary, Rank WHERE Salary.EmployeeID= Rank.EmployeeID
17

Join
To select data from two tables with the JOIN keyword.
The INNER JOIN returns all rows from both tables where there is a match.

For example: SALARY RANK

EmployeeID EmployeeID

Name Amount Position Years

SELECT Salary.EmployeeID, Salary.Name, Rank.Position FROM Salary INNER JOIN Rank ON Salary.EmployeeID= Rank.EmployeeID
18

Order by
The ORDER BY clause is used to sort the rows. To display the names in alphabetical order:
SELECT Name, Marks FROM Marksheet ORDER BY Name

To display the company names in numerical order:


SELECT Marks FROM Marksheet ORDER BY Marks

To display the names in reverse alphabetical order:


SELECT Name, Marks FROM Marksheet ORDER BY Name DESC

19

Group by
GROUP BY...
possible to find the aggregate functions like (SUM) for each individual group of column values. For example, consider Table containing expenditure by persons employed under a research project

DST2011
Date Name Item Amount

To find the total expenditure under each person: SELECT Name, SUM(Amount) FROM DST2011 GROUP BY Name In place of where we use HAVING to specify conditions HAVING SUM(amount) > 5000
20

Aggregate Functions Having Clause


Find the names of all branches where the average account

balance is more than $1,200.

select branch-name, avg (balance) from account group by branch-name having avg (balance) > 1200

21

Null Values
It is possible for tuples to have a null value, denoted by null,

for some of their attributes null signifies an unknown value or that a value does not exist. The predicate is null can be used to check for null values. E.g. Find all loan number which appear in the loan relation with null values for amount.
select loan-number from loan where amount is null

The result of any arithmetic expression involving null is null E.g. 5 + null returns null However, aggregate functions simply ignore nulls more on this shortly

22

Nested Subqueries
SQL provides a mechanism for the nesting of subqueries. A subquery is a select-from-where expression that is nested

within another query. Example :


Find all customers who have both an account and a loan at the bank. select distinct customer-name from borrower where customer-name in (select customer-name from depositor) Find all customers who have a loan at the bank but do not have an account at the bank select distinct customer-name from borrower where customer-name not in (select customer-name from depositor)
23

Modification of the Database Insertion


Add a new tuple to account

insert into account values (A-9732, Perryridge,1200) or equivalently insert into account (branch-name, balance, accountnumber)values (Perryridge, 1200, A-9732) Add a new tuple to account with balance set to null insert into account values (A-777,Perryridge, null)

24

Modification of the Database Updates


Increase all accounts with balances over $10,000 by 6%, all

other accounts receive 5%. Write two update statements: update account set balance = balance 1.06 where balance > 10000 update account set balance = balance 1.05 where balance 10000 The order is important Can be done better using the case statement (next slide)

25

Case Statement for Conditional Updates


Same query as before: Increase all accounts with balances over

$10,000 by 6%, all other accounts receive 5%. update account set balance = case when balance <= 10000 then balance *1.05 else balance * 1.06 end

26

Create Table Construct


An SQL relation is defined using the create table command: Example:

create table branch (branch-name char(15) not null, branch-city char(30), assets integer)

27

Integrity Constraints in Create Table


not null primary key (A1, ..., An) check (P), where P is a predicate

Example: Declare branch-name as the primary key

for branch and ensure that the values of assets are non-negative. create table branch (branch-name char(15), branch-city char(30) assets integer, primary key (branch-name), check (assets >= 0))

28

Drop and Alter Table Constructs


The drop table command deletes all information about the

dropped relation from the database. The after table command is used to add attributes to an existing relation. All tuples in the relation are assigned null as the value for the new attribute. The form of the alter table command is alter table r add A D where A is the name of the attribute to be added to relation r and D is the domain of A. The alter table command can also be used to drop attributes of a relation

alter table r drop A where A is the name of an attribute of relation r Dropping of attributes not supported by many databases
29

Functions
SQL has a lot of built-in functions for counting and other calculationsSELECT function(column) FROM table Types of Functions The basic types of functions are: Aggregate Functions: operate against a collection of values, but

return a single value.

AVG(column), COUNT(column), MAX(column), MIN(column), STDEV(column), SUM(column)

Scalar functions: operate against a single value, and return a single

value based on the input value.


MOD(x,y), ABS(x), ROUND(c,decimals)

30

String Operations
SQL includes a string-matching operator for comparisons on

character strings. Patterns are described using two special characters: percent (%). The % character matches any substring. underscore (_). The _ character matches any character. Find the names of all customers whose street includes the substring Main. select customer-name from customer where customer-street like %Main% Match the name Main% like Main\% escape \ SQL supports a variety of string operations such as concatenation (using ||) converting from upper to lower case (and vice versa) finding string length, extracting substrings, etc.

31

Stored Procedures
Stored Procedures
Can store procedures in the database then execute them using the call statement permit external applications to operate on the database without

knowing about internal details

32

Creating a Procedure
CREATE OR REPLACE PROCEDURE hello IS Greetings VARCHAR(20); BEGIN Greetings:= 'Hello World'; DBMS_OUTPUT.PUT_LINE(greetings); END hello; /

33

Calling a Procedure
Copy the previous procedure into SQL Plus Call it using the following commands To display output set serveroutput on size 4000 EXECUTE hello; Another way to execute it is from a command block: BEGIN hello; END; /

34

Calling a Procedure with Arguments


DECLARE price_increase NUMBER(6,2):=20; newp NUMBER(6,2):=0; BEGIN DBMS_OUTPUT.PUT_LINE('Current price '|| price_increase); increase(oldprice=>price_increase, newprice=>newp); DBMS_OUTPUT.PUT_LINE('Price after increase '|| newp); END; /

35

Creating Functions
CREATE OR REPLACE FUNCTION discount (amount NUMBER, percent NUMBER:=5) RETURN NUMBER IS BEGIN IF (amount>=0) THEN return (amount*percent/100); ELSE return(0); END IF; END discount; The IF-THEN construct / allows for error checking
36

Calling the Function


DECLARE current_amt NUMBER:=100; incorrect_amt NUMBER:=-5; BEGIN DBMS_OUTPUT.PUT_LINE(' Order and Discount'); DBMS_OUTPUT.PUT_LINE(current_amt || ' '|| discount(current_amt)); DBMS_OUTPUT.PUT_LINE(incorrect_amt||' '||discount(incorrect_amt)); END; /

37

Summary
Select . AS (alias for column) DISTINCT COUNT

Select from .. where

From AS (alias for table)

Where AND/OR BETWEEN JOIN GROUP BY ORDER BY


38

Potrebbero piacerti anche