Sei sulla pagina 1di 7

CAPITULO 6

SQL: Structured Quert Language; comprehensive database language. Tiene definiciones de


data, consultas y actualizaciones. Es un DDL y un DML.

Se divide en core specifications (que se implementan en todos los RDBMS que son SQL
compliant) y las extensiones que son modulos opcionales.

Table = relation, row = tuple, column = attribute.

SQL COMMANDS:

CREATE: Crea esquemas, tablas, tipos, dominions, vistas, asserciones y triggers.

CREATE SCHEMA nombre AUTHORIZATION ‘usuario’.

CREATE TABLE nombre o CREATE TABLE schema.nombre (atributo, tipo, NOT NULL,
DEFAULT x);

Se puede especificar de un solo las keys despues de los constraints, if any


diciendo PRIMARY KEY (atributo) o FOREIGN KEY (atributo) REFERENCES (og
atributo). También se puede agregar despues de eso ON DELETE SET xxx or ON
UPDTE CASCADE.

Se puede especificar si un atributo es PRIMARY KEY o UNIQUE directamente


desde el momento que se crea el atributo. Seria “nombreatributo, tipo,
PRIMARY KEY o UNIQUE, …”

CREATE TABLE EMPLOYEE

( …,

Dno INT NOT NULL DEFAULT 1,

CONSTRAINT EMPPK

PRIMARY KEY (Ssn),

CONSTRAINT EMPSUPERFK

FOREIGN KEY (Super_ssn) REFERENCES EMPLOYEE(Ssn)

ON DELETE SET NULL ON UPDATE CASCADE);

CREATE DOMAIN nombredomain AS data_type.

Se usa para especificar la data de un atributo directamente) Se puede usar el


nombre del domain al momento de crear atributos en lugar de un data type
específico.

CREATE TYPE: Se usa para crear user defined types or UDTs.

CHECK: restricts attributes values.

Dnumber INT NOT NULL CHECK (Dnumber > 0 AND Dnumber < 21);

Chequea que Dnumber sea mayor que 0 y menor que 21.


SELECT: retrieving information from a database. SELECT atributo FROM table WHERE
condicion. Para retrieve all attribute values se usa SELECT * FROM table WHERE condition.

DISTINCT: elimina las duplicate tuples. SELECT DISTINCT atribute FROM table;

Tambien se puede usar UNION, EXCEPT, INTERSECT

LIKE: pattern matching en strings.

BETWEEN - AND: para especificar valores en el WHERE

ORDER BY: Ordenar resultados de manera ascendiente o descendiente. SELECT atribute


FROM table WHERE condicion ORDER BY atribute ASC/DESC;

INSERT INTO: add a single tuple to a relation. INSERT INTO table VALUES (‘valor 1’, ‘valor
2’, …);

DELETE: removes tuples from a relation. DELETE FROM table WHERE condicion.

UPDATE: modify attribute values of one or more selected tuples. UPDATE table SET
atribute = new value, atributo2 = new value 2 WHERE condion;

Una SQL table is not a set of tuples porque no permite dos miembros identicos. Instead, es un
multiset de tuples.

Un tipo de constraint comun es NOT NULL.

SQL SCHEMA: identifies by a schema name. Includes authorization identifies to indicate the
user who owns the schema, and descriptiors for each element of the schema. El DBA asigna
quienes pueden crear schemas.

CATALOG: named collection of schemas. Contiene un INFORMATION_SCHEMA that provides


info de todas los esquemas en el catalogo.

BASE TABLES: relations declared through CREATE TABLE.

VIRTUAL RELATIONS: relations created through CREATE VIEW (no se fuardan en el file)

DATA TYPES:

Numeric: INT, SMALLINT, FLOAT, REAL, DOUBLE PRECISION, DEC (i, j) or NUMERIC (i, j)
donde i es precision y j la cantidad de digits despues del decimal point.

Character String: fixed length CHAR(n), varying length VARCHAR(n) donde n es el


maximo de caracteres.

Bit string: BIT(n) o BIT VARYING(n)

Boolean: puede ser TRUE, FALSE o UNKNOWN.

Date: YYYY-MM-DD. TIME es HH:MM:SS

Timestamp: incluye DATE and TIME


Interval – relative value that can be used to increment or decrement an
absolute value of a date, time or timestamp.

CONSTRAINT: Regulaciones o limitaciones que tienen los atributos. Pueden tener un nombre.
Los table constraints son los que se enseñan en el ejemplo de CREATE, y son llamados row
based porque aplican para las rows individualmente.

SELECT = Projection attribute en algebra relacional; WHERE = selection condition en algebra


relacional.

TUPLE VARIABLE: iterador den la SQL query

SELECT-PROJECT-JOIN: A query that involves only selection and join conditions plus projection
attributes

Se puede hacer esto too para que se vea mas ordenado. Se le llama renaming mechanism o
alina naming.

Tambien se puede:

 GRANT / REVOKE privileges to users.


 Create triggers, referred as active database techniques. Especifican acciones que son
automaticamente triggered por eventos i.e updates.
 Object-Relational systemas son enhaves relational systems donde se pueden crear
estructuras complejas de atributos, como los UDTs. O crear identificadores de
objetocs.
 Crear indices, pero se ocupa un privilegio especial.

CHAPTER 7

Un dato puede ser NULL cuando:

 Valor unknown
 Valor withehld o unavailable
 Not Applicable attribute

VALORES PARA AND OR NOT

Nested queries: queries that require existing values in the database be fetched and then used
in a comparison condition

Correlated queries: Whenever a condition in the WHERE clause of a nested query references
some attribute of a relation declared in the outer query, the two queries are said to be
correlated.

EXISTS: Se usa para chequear si es resultado es empty o no. SELECT atributo FROM tabla
WHERE EXISTS( otra query ). Solo funciona then con nested queries.

EXCEPT: Uso similar a EXISTS, solo que este es la primera subquery MINUS la segunda
subquery.

AS: se usa para renaming SELECT name_original AS new_name FROM tabla AS alias(ch 6)
WHERE condicion

Joined Table: table resulting from a join operation in the FROM clause of a query. SELECT
atributo FROM table A JOIN table B

NATURAL JOIN – no tiene specification Join

INNER JOIN (only pairs of tuples that match the join condition are retrieved, same as JOIN),

LEFT OUTER JOIN (every tuple in the left table must appear in the result; if it does not have a
matching tuple, it is padded with NULL values for the attributes of the right table)

RIGHT OUTER JOIN (every tuple in the right table must appear in the result; if it does not have
a matching tuple, it is padded with NULL values for the attributes of the left table)

FULL OUTER JOIN.


The keyword CROSS JOIN is used to specify the CARTESIAN PRODUCT operation

Aggregate functions are used to summarize information from multiple tuples into a single-
tuple summary. Ejemplo: COUNT, SUM, MAX, MIN, AVG son aggregate que irian despues del
SELECT y llevan como parametro atributos.

Grouping is used to create subgroups of tuples before summarization.

Partition: dividir una relationship into nonoverlapping subsets (or groups) of tuples. Se guian
por los grouping attributes.

GROUP BY hace las particiones. SELECT atributo FROM table GROUP BY atributo

HAVING es como un WHERE pero para GROUP BY. HAVING provides a condition on the
summary information regarding the group of tuples associated with each value of the grouping
attributes. SELECT atributo FOM table WHERE condicion table GROUP BY atributo HAVING
condicion para agrupar.

WITH: define una table solo para una query en particular similar a una view. WITH atributo AS
(query de donde se quieren sacar los datos de atributo) SELECT blahblahblah

CASE: Como un switch en JAVA. Se usa UPDATE tabla SET atributo = CASE WHEN condicion1
THEN valor 1 WHEN condicion2 THEN valor2 ELSE valorElse;

Existen queries revursivas alv no entiendo pero les dejo un ejemplo

Una recursive query tiene una base query as well. Cuando se llega a un fixed point donde no se
pueden agregar mas rows.

CREATE ASSERTION: se crean declarative assertions cuando se especiicacion contraints


generales. SIEMPRE tiene que ser TRUE
TRIGGERS monitorean la base de datos para ver si ciertos eventos ocurren o ciertas
condiciones son satisfacidas.

Un trigger tiene Event, Condition, Action

BEFORE/AFTER – que el trigger se ejecute ANTES de esta acciones. Es como un while/do while

WHEN – la condicion para activar el trigger

ACTION – va despues del when.

VIEW: A view in SQL terminology is a single table that is derived from other tables. A view does
not necessarily exist in physical form; it is considered to be a virtual table, in contrast to base
tables, whose tuples are always physically stored in the database.

The view is given a (virtual) table name (or view name), a list of attribute names, and a query
to specify the contents of the view.

CREATE VIEW nombre AS SELECT blahblahblah

A view is supposed to be always up-to-date; if we modify the tuples in the base tables on
which the view is defined, the view must automatically reflect these changes.

DROP VIEW nombewview borra la view.

Existen dos apporaches para implementar views eficientemente:


 Query modification: involves modifying or transforming the view query into a query on
the underlying base tables. Though it is inefficient for views defined via complex
queries that are time consuming to execute.
 View Materializaition: physically creating a temporary or permanent view table when
the view is first queried or created. Se tiene que estar updating cada vez que las base
tables se actualicen  incremental update, where DBSM puede determinar si new
tuples have been inserted, deleted or modified.
o Different strategies as to when a materialized view is updated are possible.
The immediate update strategy updates a view as soon as the base tables are
changed;
o the lazy update strategy updates the view when needed by a view query;
o the periodic update strategy updates the view periodically (in the latter
strategy, a view query may get a result that is not up-to-date).

■ A view with a single defining table is updatable if the view attributes contain the primary key
of the base relation, as well as all attributes with the NOT NULL constraint that do not have
default values specified.

■ Views defined on multiple tables using joins are generally not updatable.

■ Views defined using grouping and aggregate functions are not updatable

It is also possible to define a view table in the FROM clause of an SQL query. This is known as
an in-line view. In this case, the view is defined within the query itself.

ALTER: For base tables, the possible alter table actions include adding or dropping a column
(attribute), changing a column definition, and adding or dropping table constraints

ALTER TABLE table COMAND atributo.

DROP: Borra esquemas o tables. Puede Cascade o Restrict. SI es Cascade se borra la table y
todas las referencias a esta. Si es restrict, solo se borra la actual.

DROP SCHEMA nombre C/R;

DROP TABLE nombre C/R;

The DROP command can also be used to drop other types of named schema elements, such as
constraints or domains.

Se pueden mix too

ALTER TABLE COMPANY.EMPLOYEE DROP CONSTRAINT EMPSUPERFK CASCADE;

Potrebbero piacerti anche