Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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
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
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.
indexes (keys), specify links between tables and impose constraints between database tables.
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
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
Basic Syntax
[Note: To query data on an existing database which you are not allowed to change]
Name
Rank
Amount
Years
Select
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
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
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.
EmployeeID EmployeeID
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
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
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
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
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
$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 branch (branch-name char(15) not null, branch-city char(30), assets integer)
27
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
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
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
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
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
37
Summary
Select . AS (alias for column) DISTINCT COUNT