Sie sind auf Seite 1von 27

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS

Practica 1.4 db2


1. Creamos una base de datos llamada testdb

2. Nos conectamos a la base de datos creada

3. Creamos la tabla employees

db2 "CREATE TABLE employees (empid INTEGER, name CHAR(50), dept INTEGER)"

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS

4. Describimos la tabala que acabamos de crear

db2 describe table employees

5. Cambiamos el tipo de dato de la columna dept a un char de longitud 9

6. Volvemos a ver la definicin de la tabla para comprobar que se haya hecho el cambio

7. Tratamos de insertar algunos valores en la tabla

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS

8. Como nos manda un cdigo de error para saber que significa ese cdigo tecleamos el siguiente comando

db2 "? SQL0668N"

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS 9. Como cambiamos el tipo de dato de una columna la tabla esta en un estado pendiente entonces tenemos que usar el comando db2 reorg table

employees

10. Ahora intentaremos volver a ingresar los valores

db2 "INSERT INTO employees (EMPID, NAME, DEPT) VALUES (1, 'Adam', 'A01 '),(2, 'John', 'B01'), (3, 'Peter', 'B01'), (4, 'William', 'A01')"

11. Comprobaremos con un select que se hayan insertado los campos correctamente

db2 "select * from employees"

12. Actualizaremos un campo de la tabla

db2 "update employees set dept='A01' where name='Peter'"

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS

13. Verificamos con un select

db2 "select * from employees"

14. Borramos un registro de la tabla con la siguiente sentencia

db2 "delete employees where name='William'"

15. Listamos las tablas de la base de datos en la que estamos trabajando

db2 list tables

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS podemos ver como implcitamente un esquema es creado cuendo otro objeto es creado

16. Craremos un schema explcitamente

db2 CREATE SCHEMA myschema AUTHORIZATION db2inst1

17. Para ver todos los schemas usaremos

db2 select schemaname from syscat.schemata

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS

18. Crearemos una tabla dentro de un schema

db2 "CREATE TABLE myschema.store (storeid INTEGER, address CHAR(50))"

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS 19. listamos las tablas del schema que se cre cuando creamos la tabla anterior

db2 list tables for schema myschema

20. para ver las tablas de todos los schemas

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS

db2 list tables for all

21. crearemos una nueva tabla llamada employees dentro del schema myschema

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS y entonces tendremos dos tablas con el mismo nombre en la misma base de datos esto es posible porque una esta dentro de un schema

db2 "CREATE TABLE myschema.employees (storeid INTEGER,address CHAR(50) )"

VISTAS
22. Ahora crearemos una vista, las vistas son una forma diferente de visualizar los datos de una tabla, La vista ser de la tabla employees y queremos que la columna de Dept no se visualice

db2 "CREATE VIEW empview (employee_id, first_name) AS SELECT EMPID, NAME FROM employees"

23. Verificaremos que la vista se alla creado

db2 list tables

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS 24. Describiremos la vista creada

db2 describe table empview

25. Ahora cuando nosotros seleccionamos todos los campos de nuestra vista solo nos muestra employee_id y first_name

db2 "select * from empview"

26. Si nosotros actualizamos algn campo de nuestra vista entonces los cambios tambin se vern reflejados en la tabla original
db2 "update empview SET FIRST_NAME='Piotr' WHERE employee_id=3"

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS 27. Verificando

db2 "SELECT * FROM employees"

ALIASES
28. crearemos un alias a la tabla employees ahora podremos hacer referencia a la tabla a travs del nombre empinfo

db2 CREATE ALIAS empinfo FOR employees

29. Para ver el alias creado tenemos que usar el comando para listar tablas

db2 list tables

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS 30. Ahora si hacemos un select con el alias creado nos traer el mismo resultado que si hiciramos un select a employees

db2 "SELECT * FROM empinfo"

31. Nosotros podemos crear un alias a uno ya existente Crearemos un alias a empinfo y posteriormente listaremos las tablas y haremos un select al alias creado para que nos de cmo resultado los datos de employees

db2 CREATE ALIAS refempinfo FOR empinfo db2 list tables db2 "SELECT * FROM refempinfo

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS

Indexes
32. intentaremos crear un ndice unico a la tabla employees sobre el campo empid como no hay valores repetidos si nos permite crearlo si hubieran valores duplicados no permitira crear el ndice

db2 "CREATE UNIQUE INDEX unique_id ON employees(empid)" db2 DESCRIBE INDEXES FOR TABLE employees

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS

33. para ver la descripcin del ndice es con el siguiente comando:

db2 DESCRIBE INDEXES FOR TABLE employees

34. Ahora si intentamos insertar un registro con un empid ya existente no nos permitir hacer la transaccin

db2 "INSERT INTO employees VALUES(3, 'William', 'A01')"

35. crearemos un ndice que recolecte automticamente estadsticas para hacer mas eficientes nuestras consultas y posteriormente describiremos este ndice.

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS

db2 "CREATE INDEX idx ON employees(dept)COLLECT STATISTICS"

db2 DESCRIBE INDEXES FOR TABLE employees

Sequences
36. Crearemos una secuencia que empiece en cuatro, tenga incrementos de uno en uno y no este ciclado. Tambin insertaremos un valor usando una secuencia .

db2 "CREATE SEQUENCE emp_id START WITH 4 INCREMENT BY 1 NO CYCLE CACHE 5" db2 "INSERT INTO EMPLOYEES VALUES (NEXT VALUE FOR emp_id, 'Daniel', 'B01')"

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS

37. si insertamos otro registro veremos que el ndice se sigue incrementendo de uno en uno

db2 "INSERT INTO EMPLOYEES VALUES (NEXT VALUE FOR emp_id, 'Stan', 'B01')" db2
"SELECT

* FROM employees"

38. si nosotros cerramos la conexin con la bd y nos volvemos a conectar y volvemos a insertar un registro con una secuencia insertara un 9 porque nosotros le dijimos que guardara 5 valores en cache y solo utilizamos 4,5 los otros tres 6,7,8 se perdieron al cerrar la conexin y poreso vuelve a empezar en el numero 9

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS

Working with SQL


Create the SQL statements for the queries described below. You can then compare your answers with the suggested solutions at the end of this lab.

Find out all sales information from salesman called LEE in the Ontario- South region from the table SALES. Find out the name of all the departments that have a manager assigned to it from table DEPARTMENT.

SELECT * FROM SALES WHERE SALES_PERSON = 'LEE' AND REGION = 'Ontario-South'

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS SELECT DEPTNAME FROM DEPARTMENT WHERE MGRNO is not NULL

Section 6.1.3.1 Query 1 Using the table STAFF, rank all the people by their years of experience in descending order. For people with same YEARS, rank again by their salary in ascending order. SELECT * FROM STAFF WHERE YEARS is not NULL ORDER BY YEARS DESC, SALARY ASC

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS

Section 6.1.4.1

Find the total amount of sales for each sales person in table SALES. SELECT SALES_PERSON, SUM(SALES) AS total_sales FROM SALES GROUP BY SALES_PERSON

Count the number of male employees for each job position. SELECT JOB, COUNT(*) as TOTAL_NUM FROM EMPLOYEE WHERE SEX = 'M' GROUP BY JOB

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS

Section 6.1.5.1 Query 1


Consider you are interested in the action information (with ACTNO greater than 100) information and designer names of each project action (from table PROJACT). List this information, sorting the results alphabetically according to designers' names. SELECT DISTINCT p.PROJNO, FIRSTNME, LASTNAME, p.ACSTDATE, ep.EMSTDATE FROM EMPLOYEE e, EMPPROJACT ep, PROJACT p WHERE e.EMPNO = ep.EMPNO AND ep.PROJNO = p.PROJNO AND e.JOB = DESIGNER AND p.ACTNO > 100 ORDER BY FIRSTNME, LASTNAME

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS Join tables EMPLOYEE and DEPARTMENT, considering WORKDEPT in EMPLOYEE is the FK referring to DEPTNO the PK in table DEPARTMENT. Save the results, and repeat this query, but use LEFT OUTER JOIN, RIGHT OUTER JOIN and FULL OUTER JOIN instead. Compare the results.

SELECT * FROM employee INNER JOIN DEPARTMENT ON employee.WORKDEPT = DEPARTMENT .DEPTNO

Section 6.2.1.1
Our company just started a new department called FOO with department number K47, and 'E01' as ADMRDEPT. Insert this record into table DEP ARTMENT. INSERT INTO DEPARTMENT (DEPTNO, DEPTNAME, ADMRDEPT) VALUES ('K47', 'FOO', 'E01')

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS

Create a new table called D11_PROJ with the same structure of table PROJECT and add to it data about all projects from department D11.

CREATE TABLE D11_PROJ LIKE PROJECT

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS INSERT INTO D11_PROJ SELECT * FROM PROJECT WHERE DEPTNO = 'D11'

Section 6.2.2.1
Try to update Paul's EDLEVEL to 'NULL', see what happens. UPDATE EMPLOYEE SET EDLEVEL = NULL WHERE EMPNO = 300001

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS

Try to update Paul's WORKDEPT to 'Z11', see what happens.

UPDATE EMPLOYEE SET WORKDEPT = 'Z11' WHERE EMPNO = 300001

Section 6.2.3.1 Try to delete department 'E21' from table DEPARTMENT


DELETE FROM DEPARTMENT WHERE DEPTNO = 'E21'

CORDERO CASTRO CSAR ARMANDO NOLLA SALTIEL CARLOS

Das könnte Ihnen auch gefallen