SQL (I) Tema 3.

Slides:



Advertisements
Similar presentations
Structured Query Language (SQL)
Advertisements

Using DDL Statements to Create and Manage Tables
11 Copyright © Oracle Corporation, All rights reserved. Managing Tables.
9 Copyright © 2004, Oracle. All rights reserved. Using DDL Statements to Create and Manage Tables.
Data Definition Language (DDL)
EL Modelo Objeto-Relacional Por: ANGELICA URRUTIA GGR/2000.
1 I Esempio di constraints. 2 DROP TABLE regions; CREATE TABLE regions ( region_id NUMBER CONSTRAINT region_id_nn NOT NULL, region_name VARCHAR2(25) );
Virtual training week 4 structured query language (SQL)
Chapter Thirteen Sequences Dr. Chitsaz Objectives: Sequence objects Create and use sequences Application of sequences.
CREATE TABLE famille( ( NomCol1 type [NOT NULL], … NomColn type [NOT NULL], PRIMARY KEY (NomColi, NomColj,…), FOREIGN KEY (NomColk, NomColv,…)REFERENCES.
MySQL Servidor de Bases de Datos Software Libre Ambientes Windows & Unix.
Bases de Datos 1 Prof. Daniel Obando Fuentes. CREANDO UNA BASE DE DATOS CREATE DATABASE dbname;
10 Copyright © 2004, Oracle. All rights reserved. Creating Other Schema Objects.
SQL components In Oracle. SQL in Oracle SQL is made up of 4 components: –DDL Data Definition Language CREATE, ALTER, DROP, TRUNCATE. Creates / Alters.
Murali Mani SQL DDL and Oracle utilities. Murali Mani Datatypes in SQL INT (or) INTEGER FLOAT (or) REAL DECIMAL (n, m) CHAR (n) VARCHAR (n) DATE, TIME.
Copyright س Oracle Corporation, All rights reserved. 13 Other Database Objects.
INTEGRITY Enforcing integrity in Oracle. Oracle Tables mrobbert owner granted access.
Database Management System LICT 3011 Eyad H. Elshami.
Data Definition, Relational Manipulation and Data Control Using SQL.
SQL Basics. SQL SQL (Structured Query Language) is a special-purpose programming language designed from managing data in relational database management.
ORACLE SQL. Overview Personal DBMS Vs Client/Server DBMS Oracle 8 Environment SQL – syntax and examples PL/SQL-introduction.
Chapter 6 Additional Database Objects
I Copyright © 2004, Oracle. All rights reserved. Introduction.
Constraints  Constraints are used to enforce rules at table level.  Constraints prevent the deletion of a table if there is dependencies.  The following.
13 Other Database Objects Important Legal Notice:  Materials on this lecture are from a book titled “Oracle Education” by Kochhar, Gravina, and Nathan.
SQL Server 7.0 Maintaining Referential Integrity.
Copyright © 2004, Oracle. All rights reserved. Lecture 3: Creating Other Schema Objects Lecture 3: Creating Other Schema Objects ORACLE.
Oracle Database Administration
12 Copyright © Oracle Corporation, All rights reserved. Other Database Objects.
11 Copyright © 2007, Oracle. All rights reserved. Creating Other Schema Objects.
Chapter 6 Additional Database Objects Oracle 10g: SQL.
Chapter 5 Sequences.
SQL SQL Server : Overview SQL : Overview Types of SQL Database : Creation Tables : Creation & Manipulation Data : Creation & Manipulation Data : Retrieving.
1 Structured Query Language (SQL). 2 Contents SQL – I SQL – II SQL – III SQL – IV.
Nitin Singh/AAO RTI ALLAHABAD 1 SQL Nitin Singh/AAO RTI ALLAHABAD 2 OBJECTIVES §What is SQL? §Types of SQL commands and their function §Query §Index.
Database Programming Sections 11 & 12 – Creating, and Managing Views, Sequences, Indexes, and Synonymns.
SQL Basics. 5/27/2016Chapter 32 of 19 Naming SQL commands are NOT case sensitive SQL commands are NOT case sensitive But user identifier names ARE case.
SQL: DDL. SQL Statements DDL - data definition language –Defining and modifying data structures (metadata): database, tables, views, etc. DML - data manipulation.
BIS Database Systems School of Management, Business Information Systems, Assumption University A.Thanop Somprasong Chapter # 7 Introduction to Structured.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
SQL: Advanced topics Prof. Weining Zhang Cs.utsa.edu.
1 SQL - II Data Constraints –Applying data constraints Types of data constraints –I/O constraints The PRIMARY KEY constraints The FOREIGN KEY constraints.
Database Lab Lecture 1. Database Languages Data definition language ( DDL ) Data definition language –defines data types and the relationships among them.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI
DBSQL 5-1 Copyright © Genetic Computer School 2009 Chapter 5 Structured Query Language.
Database Fundamental & Design by A.Surasit Samaisut Copyrights : All Rights Reserved.
Database Programming Sections 11 & 12 –Sequences, Indexes, and Synonymns.
5. Simple SQL using Oracle1 Simple SQL using Oracle 5. Working with Tables: Data management and Retrieval 6. Working with Tables: Functions and Grouping.
AL-MAAREFA COLLEGE FOR SCIENCE AND TECHNOLOGY INFO 232: DATABASE SYSTEMS CHAPTER 7 (Part II) INTRODUCTION TO STRUCTURED QUERY LANGUAGE (SQL) Instructor.
1 SQL-2 Tarek El-Shishtawy Professor Ass. Of Computer Engineering.
© 2009 Punjab University College of Information Technology (PUCIT) September 8, 2009 Slide 1 (SQL) Other Database Objects Asif Sohail University of the.
Transactions, Roles & Privileges Oracle and ANSI Standard SQL Lecture 11.
Altering Tables and Constraints Database Systems Objectives Add and modify columns. Add, enable, disable, or remove constraints. Drop a table. Remove.
Relational Database Management System(RDBMS) Structured Query Language(SQL)
Database Programming Sections 12 – Sequences, Indexes, and Synonymns.
7 1 Database Systems: Design, Implementation, & Management, 7 th Edition, Rob & Coronel 7.6 Advanced Select Queries SQL provides useful functions that.
Oracle sql Online Training By SMART MIND ONLINE TRAINING Website:
The Basics of Data Manipulation
Insert, Update and the rest…
ITEC 313 Database Programming
Chapter 5 Sequences.
The Basics of Data Manipulation
Database Programming Sections 11-12–Sequences, Indexes & Synonyms, Controlling User Access, Creating & Revoking Object Privileges 11/25/08.
DATABASE SQL= Structure Query Language مبادئ قواعد بيانات
مقدمة في قواعد البيانات
Rob Gleasure robgleasure.com
Index Note: A bolded number or letter refers to an entire lesson or appendix. A Adding Data Through a View ADD_MONTHS Function 03-22, 03-23,
Contents Preface I Introduction Lesson Objectives I-2
Instructor: Samia arshad
Presentation transcript:

SQL (I) Tema 3

¿Qué es SQL? SQL: Structured Query Language (lenguaje de consultas estructurado) Específico para bases de datos relacionales No es imperativo, es declarativo

Funciones de SQL Definición de datos (LDD) Manipulación de datos (LMD) Control de acceso (LCD) Gestión de Integridad Concurrencia

Instrucciones SQL LDD LMD Create Alter Drop Select Insert Update Delete

Instrucciones SQL LCD Gestión de la integridad Grant Revoke Commit Rollback

Tipos de datos Alfanuméricos Numéricos Fecha Binarios Otros CHAR NUMBER DATE RAW ROWID VARCHAR2 FLOAT LONG RAW VARCHAR BLOB NCHAR CLOB NVARCHAR2 NLOB LONG BFILE

Create Table CREATE TABLE nombre_tabla( COLUMNA TIPO [NOT NULL] [UNIQUE] [PRIMARY KEY] [DEFAULT valor] [REFERENCES Nomtabla][columna[,columna]][ON DELETE CASCADE]] [CHECK condicion], COLUMNA TIPO [NOT NULL], . . . {CONSTRAINT nombre_clave_primaria PRIMARY KEY (columnas_clave)} {CONSTRAINT nombre_clave_foránea FOREIGN KEY(columnas_clave) REFERENCES tabla_detalle( columnas_clave ) {ON DELETE CASCADE} } ) {TABLESPACE tablespace_de_creación} {STORAGE( INITIAL XX{K|M} NEXT XX{K|M} )}

Create Table Ejemplo: CREATE TABLE FACTURA( REFERENCIA VARCHAR2(10) NOT NULL, DESCRIPCION VARCHAR2(50), C_PAIS NUMBER(3), C_CLIENTE NUMBER(5), IMPORTE NUMBER(12), CONSTRAINT PK_FACTURA PRIMARY KEY( REFERENCIA ), CONSTRAINT FK_CLIENTE FOREIGN KEY(C_PAIS,C_CLIENTE) REFERENCES CLIENTE( C_PAIS, C_CLIENTE) ON DELETE CASCADE ) TABLESPACE tab_facturas STORAGE( INITIAL 1M NEXT 500K );

Create Index CREATE {UNIQUE} INDEX nombre_índice ON tabla( columnas_indexadas ) {TABLESPACE tab_indices} {STORAGE( INITIAL XX{K|M} NEXT XX{K|M} )} Ejemplo: CREATE INDEX ind_factura_cliente ON FACTURA( C_PAIS, C_CLIENTE ) TABLESPACE tab_factura_ind STORAGE( INITIAL 500K NEXT 500K );

Drop DROP tipo_objeto objeto_a_borrar. Ejemplo: DROP TABLE FACTURA; DROP SEQUENCE COD_CLIENTE; DROP SYNONYM BILL; DROP VIEW TOTAL_FACTURA_CLIENTE; DROP TABLESPACE tab_indices;

Truncate TRUNCATE nombre_tabla {DROP|REUSE STORAGE} Ejemplo: TRUNCATE FACTURA DROP STORAGE; TRUNCATE CLIENTE;

Alter ALTER tipo_objeto nombre_objeto Cláusulas específicas de cada tipo de ALTER; Ejemplo: ALTER TABLE nombretabla [ADD (columna[,columna]...) [MODIFY (columna[,columna]...) [DROP COLUMN (columna[,columna]...) [ADD CONSTRAINT restriccion] [ADD CONSTRAINT restriccion];

Create Sequence CREATE SEQUENCE nombre_secuencia {START WITH entero} {INCREMENT BY entero} {MAXVALUE entero | NOMAXVALUE} {MINVALUE entero | NOMINVALUE } {CYCLE | NOCYCLE};

Create Sequence CREATE SEQUENCE REF_FACTURA START WITH 1 Ejemplo: CREATE SEQUENCE REF_FACTURA START WITH 1 INCREMENT BY 1 MAXVALUE 999999 MINVALUE 1; CREATE SEQUENCE COD_CLIENTE INCREMENT BY 10; CREATE SEQUENCE COD_PAIS INCREMENT BY 10 CYCLE;

Operadores en SQL Aritméticos Concatenación

Operadores en SQL (II) Lógicos

Insert Sintaxis 1: Sintaxis 2: INSERT INTO tabla{( campos )} VALUES( lista de valores ); Sintaxis 2: SELECT . . .

Insert Ejemplos: INSERT INTO FACTURA VALUES( 'A111', 'Factura nueva', 1, 5, 50000 ); INSERT INTO FACTURA( C_PAIS, REFERENCIA, IMPORTE, C_CLIENTE, DESCRIPCIPCION ) VALUES( 1, 'A111', 50000, 5, 'Factura nueva' ); INSERT INTO FACTURA( REFERENCIA, IMPORTE ) VALUES( 'A111', 50000 ); INSERT INTO FACTURA( C_PAIS, C_CLIENTE ) SELECT C_PAIS, C_CLIENTE FROM CLIENTE;

Select Sintaxis: SELECT {DISTINCT} columnas FROM tabla{,tabla,...|INNER JOIN tabla2 ON tabla.columna=tabla2.columna} {WHERE condición} {GROUP BY agrupación} {HAVING condición agrupada} {ORDER BY ordenación};

Select Ejemplos From: Ejemplos Where: FROM FACTURA FAC FROM FACTURA FAC, CLIENTE CLI FROM DUAL FROM ( SELECT C_CLIENTE FROM FACTURA ) CLIENTE_FAC Ejemplos Where: WHERE FACTURA.REFERENCIA = 'AA3455' WHERE FACTURA.C_CLIENTE IS NULL WHERE C_CLIENTE BETWEEN '12' AND '20' WHERE C_CLIENTE IS NULL AND REFERENCIA IN ('AA23344', 'BB23345') WHERE C_CLIENTE != 55 OR REFERENCIA LIKE 'AA%5_'

Select Ejemplos Order by ORDER BY REFERENCIA ASC ORDER BY REFERENCIA DESC, C_CLIENTE DES, IMPORTE ASC ORDER BY C_CLIENTE ORDER BY 1, C_CLIENTE, 2 ORDER BY TRUNC( '1-JAN-2001'+1, 'MON' ) ORDER BY 1.1+3-5/44.3 -- no tiene sentido ordenar por una cte.

Select Ejemplo producto cartesiano Ejemplo Inner Join SELECT * FROM pedidos,clientes WHERE pedidos.clie=clientes.numclie Ejemplo Inner Join FROM pedidos INNER JOIN clientes ON pedidos.clie = clientes.numclie

Delete Sintaxis: Ejemplos: DELETE {FROM} tabla {WHERE condición}; DELETE FROM FACTURA WHERE REFERENCIA = 'A111'; DELETE FACTURA; DELETE FACTURA WHERE C_PAIS = 1 AND C_CLIENTE = 5; DELETE FROM FACTURA WHERE REFERENCIA NOT IN ( SELECT REFERENCIA FROM FACTURA WHERE C_CLIENTE = 4 ); DELETE FROM FACTURA WHERE C_CLIENTE != 4;

Update Sintaxis: UPDATE tabla SET campo = valor, campo = valor, . . . {WHERE condición};

Update Ejemplos: UPDATE FACTURA SET IMPORTE = 1000 WHERE C_PAIS = 1 AND C_CLIENTE = 5; SET IMPORTE = IMPORTE * 0.5 UPDATE FACTURA F1 SET IMPORTE = ( SELECT AVG(IMPORTE) * 1.10 FROM FACTURA F2 WHERE F1.C_PAIS = F2.C_PAIS AND F1.C_CLIENTE = F2.C_CLIENTE ); SET IMPORTE = ( SELECT AVG(F2.IMPORTE) + F1.IMPORTE