Sunteți pe pagina 1din 12

22/12/2011

Porque SQL?
SQL es un lenguaje de muy alto nivel

Introduction to SQL
Select-From-Where Statements Subqueries Grouping and Aggregation
1

Dice que hacer en lugar de cmo hacerlo Evita mucha detalles de la manipulacin de datos necesarios en lenguajes como C++ o Java.

DMS (Database management system) determina la mejor manera de ejecutar nuestra consulta.
2

Select-From-Where
SELECT atributos FROM una o ms tablas WHERE condicin referente a las tuplas de la tabla

Ejemplo
Nuestras consultas se basarn en el siguiente esquma
El subrayado indica las llaves.

Beers(name, manf) Bars(name, addr, license) Drinkers(name, addr, phone) Likes(drinker, beer) Sells(bar, beer, price) Frequents(drinker, bar)
3 4

22/12/2011

Example
Usando Beers(name, manf), que cervezas son hechas por Anheuser-Busch? SELECT name FROM Beers WHERE manf = Anheuser-Busch;
Note SQL usa comillas simples para cadenas. SQL es case-insensitive, excepto dentro de las cadenas.

Significado de una query simple


Inicia con la relacin en la clusula FROM. Aplica la seleccin indicada por la clusula WHERE.

Aplica la proyeccin indicada por la clusula SELECT.

* En la clusula SELECT
* en el SELECT significa todos los atributos de esta relacin Example using Beers(name, manf): SELECT * FROM Beers
WHERE manf = Anheuser-Busch;

Renombrar Atributos
Si deseas que el resultado tenga diferentes nombres de atributos, usa AS <nombre nuevo> para renombrar un atributo. Ejemplo: Beers(name, manf): SELECT name AS beer, manf FROM Beers WHERE manf = Anheuser-Busch
7 8

22/12/2011

Resultado del Query:


beer Bud manf Anheuser-Busch

Expresiones en la clusula SELECT


Cualquier expresin que tenga sentido puede aparecer como un elemento de la clausula SELECT clause. Ejemplo: para Sells(bar, beer, price): SELECT bar, beer, price * 114 AS priceInYen

Bud Lite Michelob ...

Anheuser-Busch Anheuser-Busch ...

FROM Sells;
9 10

Result of Query
bar Joes Sues beer Bud Miller priceInYen 285 342

Otro Ejemplo: Expresiones Constantes


De Likes(drinker, beer) :

SELECT drinker, likes Bud AS whoLikesBud FROM Likes WHERE beer = Bud;
11 12

22/12/2011

Resultado del Query


drinker whoLikesBud Sally likes Bud

Condiciones Complejas en la Clausula WHERE


De Sells(bar, beer, price), encontrar el precio que Joes Bar cobra por Bud: SELECT price FROM Sells
Note como se obtiene Una comilla simple en una cadena.

Fred

likes Bud

WHERE bar = Joes Bar AND beer = Bud;


13 14

Patrones
La clusula WHERE puede tener condiciones en las cuales una cadena se compara con un patrn, para ver si corresponde. Forma general: <Atributo> LIKE <patron> or <Atributo> NOT LIKE <patron> Patron es cadena con % = cualquier cadena; _ = cualquier caracter
15

Ejemplo
De Drinkers(name, addr, phone) encuentre los bebedores con los dgitos 555 en su telfono: SELECT name FROM Drinkers WHERE phone LIKE %555%;
16

22/12/2011

Consultas de varias relaciones


Consultas interesantes presentan combinaciones de ms de una relacin. Podemos direccionar varia relaciones en una consulta listandolas en la clausula FROM. Para diferenciar atributos con el mismo nombre <relacion>.<atributo>
17

Ejemplo
Utilizando las relacones Likes(drinker, beer) y Frequents(drinker, bar), encuentre las cervezas que le gustan al menos a una persona que frecuenta Joes Bar. SELECT beer FROM Likes, Frequents WHERE bar = Joes Bar AND Frequents.drinker = Likes.drinker;
18

Expecificando Variables para una tupla


Algunas veces, un query necesita emplear dos copias de la misma relacin. Diferencia las copias siguiendo el nombre de la relacin por el nombre de una variable en la calusula FROM. Siempre es una opcin renombrar las relaciones de esta manera.
20

Ejemplo
De Beers(name, manf), encuentra todos los pares de cervezas del mismo fabricante.
Produzca pares en orden alfabtico, ejemplo(Bud,Miller), not (Miller, Bud).

SELECT b1.name, b2.name FROM Beers b1, Beers b2 WHERE b1.manf = b2.manf AND b1.name < b2.name;
21

22/12/2011

Subqueries
Un SELECT-FROM-WHERE entre parentesis (subquery ) puede utilizarse como un valor en diferentes lugares como las clausulas FROM y WHERE. Ejemplo: en lugar de una relacin en la clausula FROM, podemos colocar otro query, y entonces hacer consultas sobre su resultado.
Conviene utilizar variables para nombrar las tuplas del res ultado.
22

Subqueries que regreasn una tupla


Si un subquery garantiza producir una tupla, entonces el subquery puede ser utilizado como un valor.
Generalmente, las tuplas tienen un componente. Un RUN-time error ocurre si no hay tupla o hay ms de una tupla.

23

Example
De Sells(bar, beer, price), encuentra los bares que venden Miller por el mismo precio que Joe vende Bud. Dos queries seguramente trabajaran:
1. Encontrar el precio que Joe cobra por Bud. 2. Encontrar los bares que s irven Miller a es e precio.

Query + Subquery Solution


SELECT bar FROM Sells WHERE beer = Miller AND price = (SELECT price FROM Sells El precio al cual Joe vende Bud WHERE bar = Joes Bar AND beer = Bud);
25

24

22/12/2011

El Operador IN
<tupla> IN <relacion> es verdadera s i y s olo s i la tupla es un miembro de la relacin.
<tupla> NOT IN <relacion> significa lo opuesto.

Ejemplo
De Beers(name, manf) y Likes(drinker, beer), encuentre el nombre y fabricante de cada cerveza que le gusta a Fred. SELECT *
FROM Beers WHERE name IN (SELECT beer
The set of beers Fred likes

IN-expres iones pueden aparecer en la clus ula WHERE. La <relacion> es con frecuencia un s ubquery.

FROM Likes
WHERE drinker = Fred);
27

26

The Exists Operator


EXISTS( <relation> ) is true if and only if the <relation> is not empty. Example: From Beers(name, manf) , find those beers that are the unique beer by their manufacturer.

Example Query with EXISTS


SELECT name FROM Beers b1
Set of beers with the same manf as b1, but not the same beer

Notice scope rule: manf refers to closest nested FROM with a relation having that attribute.

WHERE NOT EXISTS( SELECT * FROM Beers WHERE manf = b1.manf AND name <> b1.name);

Notice the SQL not equals operator

29

30

22/12/2011

The Operator ANY


x = ANY( <relation> ) is a boolean condition true if x equals at least one tuple in the relation. Similarly, = can be replaced by any of the comparison operators.
Example: x >= ANY( <relation> ) means x is not the smallest tuple in the relation.
Note tuples must have one component only.
31

The Operator ALL


Similarly, x <> ALL( <relation> ) is true if and only if for every tuple t in the relation, x is not equal to t.
That is, x is not a member of the relation.

The <> can be replaced by any comparison operator. Example: x >= ALL( <relation> ) means there is no tuple larger than x in the relation.
32

Example
From Sells(bar, beer, price), find the beer(s) sold for the highest price. SELECT beer
FROM Sells WHERE price >= ALL( SELECT price FROM Sells);

Controlling Duplicate Elimination


Force the result to be a set by SELECT DISTINCT . . . Force the result to be a bag (i.e., dont eliminate duplicates) by ALL, as in . . . UNION ALL . . .

price from the outer Sells must not be less than any price.

33

34

22/12/2011

Example: DISTINCT
From Sells(bar, beer, price), find all the different prices charged for beers: SELECT DISTINCT price FROM Sells;

Aggregations
SUM, AVG, COUNT, MIN, and MAX can be applied to a column in a SELECT clause to produce that aggregation on the column. Also, COUNT(*) counts the number of tuples.

Notice that without DISTINCT, each price would be listed as many times as there were bar/beer pairs at that price.
35

36

Example: Aggregation
From Sells(bar, beer, price), find the average price of Bud: SELECT AVG(price) FROM Sells WHERE beer = Bud;

Eliminating Duplicates in an Aggregation


Use DISTINCT inside an aggregation. Example: find the number of different prices charged for Bud: SELECT COUNT(DISTINCT price) FROM Sells WHERE beer = Bud;
37 38

22/12/2011

Grouping
We may follow a SELECT-FROMWHERE expression by GROUP BY and a list of attributes. The relation that results from the SELECT-FROM-WHERE is grouped according to the values of all those attributes, and any aggregation is applied only within each group.
41

Example: Grouping
From Sells(bar, beer, price), find the average price for each beer: SELECT beer, AVG(price) FROM Sells GROUP BY beer;

42

Example: Grouping
From Sells (bar, beer, price) and Frequents (drinker, bar), find for each drinker the average price of Bud at the bars they frequent: Compute drinker-barSELECT drinker, AVG(price)
FROM Frequents , Sells WHERE beer = Bud AND Frequents .bar = Sells .bar GROUP BY drinker;
43

Restriction on SELECT Lists With Aggregation


If any aggregation is used, then each element of the SELECT list must be either:
1. Aggregated, or
2. An attribute on the GROUP BY list.

price for Bud tuples first, then group by drinker.

44

10

22/12/2011

Illegal Query Example


You might think you could find the bar that sells Bud the cheapest by: S E LECT ba r, MIN(price) FROM S ells WHE RE beer = Bud ; But this query is illegal in SQL.
45

HAVING Clauses
HAVING <condition> may follow a GROUP BY clause. If so, the condition applies to each group, and groups not satisfying the condition are eliminated.

46

Example: HAVING
From Sells(bar, beer, price) and Beers(name, manf), find the average price of those beers that are either served in at least three bars or are manufactured by Petes.

Solution
SELECT beer, AVG(price) FROM Sells
Beer groups with at least 3 non-NULL bars and also beer groups where the manufacturer is Petes.

GROUP BY beer HAVING COUNT(bar) >= 3 OR beer IN (SELECT name FROM Beers WHERE manf = Petes);
47

Beers manufactured by Petes.

48

11

22/12/2011

Requirements on HAVING Conditions


These conditions may refer to any relation or tuple-variable in the FROM clause. They may refer to attributes of those relations, as long as the attribute makes sense within a group; i.e., it is either:
1. A grouping attribute, or 2. Aggregated.
49

Ejercicios
Utilizando la base de datos de Equipo
Obtn el nmero de PC, Porttiles e impresoras por fabricante Obtn los distintos precios para un producto

Obtn el precio promedio para cada PC

50

12

S-ar putea să vă placă și