A basic create statement for a simple student table would look like the following.



Similar documents
Oracle Database 10g Express

A Brief Introduction to MySQL

SQL. Short introduction

CSI 2132 Lab 3. Outline 09/02/2012. More on SQL. Destroying and Altering Relations. Exercise: DROP TABLE ALTER TABLE SELECT

SQL NULL s, Constraints, Triggers

Programming with SQL

5. CHANGING STRUCTURE AND DATA

Oracle Database: SQL and PL/SQL Fundamentals

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

Access Queries (Office 2003)

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

Oracle SQL. Course Summary. Duration. Objectives

Oracle Database 10g: Introduction to SQL

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

Oracle Database 12c: Introduction to SQL Ed 1.1

Chapter 9 Joining Data from Multiple Tables. Oracle 10g: SQL

Information Systems SQL. Nikolaj Popov

Oracle Database: SQL and PL/SQL Fundamentals NEW

3.GETTING STARTED WITH ORACLE8i

Oracle 10g PL/SQL Training

Teach Yourself InterBase

In This Lecture. Security and Integrity. Database Security. DBMS Security Support. Privileges in SQL. Permissions and Privilege.

Oracle Database: SQL and PL/SQL Fundamentals

Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.

SQL Programming. CS145 Lecture Notes #10. Motivation. Oracle PL/SQL. Basics. Example schema:

Using Multiple Operations. Implementing Table Operations Using Structured Query Language (SQL)

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

Database Query 1: SQL Basics

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

How To Create A Table In Sql (Ahem)

CS143 Notes: Views & Authorization

Advance DBMS. Structured Query Language (SQL)

2. Oracle SQL*PLUS Winter Some SQL Commands. To connect to a CS server, do:

Performance Implications of Various Cursor Types in Microsoft SQL Server. By: Edward Whalen Performance Tuning Corporation

SQL Simple Queries. Chapter 3.1 V3.0. Napier University Dr Gordon Russell

CSC 443 Data Base Management Systems. Basic SQL

Lab 9 Access PreLab Copy the prelab folder, Lab09 PreLab9_Access_intro

SQL Tables, Keys, Views, Indexes

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

SQL SELECT Query: Intermediate

DBMS Questions. 3.) For which two constraints are indexes created when the constraint is added?

Introduction to Microsoft Jet SQL

P_Id LastName FirstName Address City 1 Kumari Mounitha VPura Bangalore 2 Kumar Pranav Yelhanka Bangalore 3 Gubbi Sharan Hebbal Tumkur

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

A table is a collection of related data entries and it consists of columns and rows.

5.1 Database Schema Schema Generation in SQL

The Relational Model. Why Study the Relational Model?

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA

Relational Database: Additional Operations on Relations; SQL

History of SQL. Relational Database Languages. Tuple relational calculus ALPHA (Codd, 1970s) QUEL (based on ALPHA) Datalog (rule-based, like PROLOG)

Using SQL Queries to Insert, Update, Delete, and View Data: Joining Multiple Tables. Lesson C Objectives. Joining Multiple Tables

EECS 647: Introduction to Database Systems

Learning MySQL! Angola Africa SELECT name, gdp/population FROM world WHERE area > !

The Relational Model. Why Study the Relational Model? Relational Database: Definitions

Lecture 6. SQL, Logical DB Design

Developing SQL and PL/SQL with JDeveloper

Handling Exceptions. Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 8-1

Optimizing the Performance of the Oracle BI Applications using Oracle Datawarehousing Features and Oracle DAC

SQL Data Definition. Database Systems Lecture 5 Natasha Alechina

Examine the structure of the EMPLOYEES table: EMPLOYEE_ID NUMBER Primary Key FIRST_NAME VARCHAR2(25) LAST_NAME VARCHAR2(25)

SQL Server An Overview

Oracle 12c New Features For Developers

Microsoft Access 3: Understanding and Creating Queries

Mul$media im Netz (Online Mul$media) Wintersemester 2014/15. Übung 03 (Nebenfach)

Instant SQL Programming

Guide to SQL Programming: SQL:1999 and Oracle Rdb V7.1

Oracle Database: SQL and PL/SQL Fundamentals NEW

RDBMS Using Oracle. Lecture Week 7 Introduction to Oracle 9i SQL Last Lecture. kamran.munir@gmail.com. Joining Tables

D61830GC30. MySQL for Developers. Summary. Introduction. Prerequisites. At Course completion After completing this course, students will be able to:

Using AND in a Query: Step 1: Open Query Design

Concepts Design Basics Command-line MySQL Security Loophole

Chapter 2: Security in DB2

Database Administration with MySQL

Guide to Performance and Tuning: Query Performance and Sampled Selectivity

Managing Objects with Data Dictionary Views. Copyright 2006, Oracle. All rights reserved.

SQL Injection. The ability to inject SQL commands into the database engine through an existing application

ATTACHMENT 6 SQL Server 2012 Programming Standards

David Dye. Extract, Transform, Load

Darshan Institute of Engineering & Technology PL_SQL

SQL Server. 1. What is RDBMS?

SQL Server Database Coding Standards and Guidelines

14 Triggers / Embedded SQL

Introduction to SQL and database objects

2. Which of the following declarations is invalid? Mark for Review (1) Points

In This Lecture. SQL Data Definition SQL SQL. Notes. Non-Procedural Programming. Database Systems Lecture 5 Natasha Alechina

Migrate Topaz databases from One Server to Another

An Introduction to PL/SQL. Mehdi Azarmi

Resources You can find more resources for Sync & Save at our support site:

DbSchema Tutorial with Introduction in SQL Databases

MySQL for Beginners Ed 3

D B M G Data Base and Data Mining Group of Politecnico di Torino

Developing Web Applications for Microsoft SQL Server Databases - What you need to know

Choosing a Data Model for Your Database

Programming Database lectures for mathema

Query-by-Example (QBE)

Unit 10: Microsoft Access Queries

More on SQL. Juliana Freire. Some slides adapted from J. Ullman, L. Delcambre, R. Ramakrishnan, G. Lindstrom and Silberschatz, Korth and Sudarshan

Transcription:

Creating Tables A basic create statement for a simple student table would look like the following. create table Student (SID varchar(10), FirstName varchar(30), LastName varchar(30), EmailAddress varchar(30)); The above example creates a table with all text fields. For other data types refer to the Oracle Data Types handout. Now we want to make sure that null values are not inserted into this table. create table Student (SID varchar(10) not null, FirstName varchar(30) not null, LastName varchar(30) not null, EmailAddress varchar(30)); Now if you want to make SID as a primary key you could do it in two ways either Add the constraint at the time of creation Alter the existing table and add the primary key constraint At the time of creation The following SQL statement will add the constraint at the time of the creation create table Student (SID varchar(10) not null primary key, FirstName varchar(30) not null, LastName varchar(30) not null, EmailAddress varchar(30)); If you want to name your constraint the syntax will look like the following create table Student (SID varchar(10) not null constraint pkstudent primary key, FirstName varchar(30) not null, LastName varchar(30) not null, EmailAddress varchar(30)); For an existing Table For an existing table, you could add constraints by using the alter table syntax Alter table student add constraint pkstudent primary key(sid) Page 1

Now if you want to remove constraints you would use some thing like this as shown below alter table student drop constraint pkstudent Lets say we create an another table called StudentScores that references the SID in Student as a foreign key. You could create the table with the following syntax Create table StudentScores(SID varchar(10) not null references Student(SID), Score number(10)) You can also name the constraint so that you could drop it in the future for any reason. Create table StudentScores(SID varchar(10) not null constraint fkstudent references Student(SID), Score number(10)) Generally the syntax for each of the columns in a database is like this. [constraint <constraint_name>] [not] null check (< condition >) unique primary key refereneces <table_name>[(column_name>)] [on delete cascade] [on delete restrict] [on delete set default] [on update cascade] [on update restrict] [on update set default] CASCADE Policy - If a record that is being referenced is DELETED then delete the referencing record as well. If a Primary Key is UPDATED (changed) then update the corresponding Foreign Key as well. RESTRICT Policy - A record can not be DELETED if there is a Foreign Key referencing it. A Primary Key can not be UPDATED if there is a Foreign Key referencing it. A record with a Foreign Key can not be INSERTED (restrict insert) if it has a Foreign Key not referencing an exiting Primary Key. Page 2

DEFAULT Policy - If a record that is being referenced is DELETED then set the corresponding Foreign Key to some default value, usually NULL. If a Primary Key is UPDATED then set the corresponding Foreign Key to a default value, usually to NULL. Adding columns to existing tables Some times it is necessary to add new columns to the database, For this you could use the Alter table syntax as follows alter table StudentScores add ExamName varchar(10) Delete Tables If you want to remove all the data in the Table, you could use drop table syntax drop table StudentScores This is useful if you want to recreate the table. Be careful with the drop statements as you will not be able to retrieve the data. Delete Rows Sometimes you might need to delete some specific Rows in a table. For this purpose you could use the delete command in SQL. Lets say we just want to delete all the rows in the Students table, your SQL would look something like this. delete from students; After you execute this statement all the data in the students is gone, also all the data in the child tables might be also deleted if we have used the cascade policy when creating the tables. Lets say we just want to delete the student with 1111111111 as his ID, the SQL would look something like this delete from students where SID= 1111111111 ; Page 3

So basically you could use the similar where clause as you use in select statements to perform even delete queries. Truncate Tables If you want to delete all the data in a table, but keep the structure intact, you could use truncate instead of delete. Truncate will eliminate fragmentation of the tablespace. Example, truncate table students; Creating tables from Other Tables You could create tables from other tables by using select statements. So it means you could store the output of any of your select statements as another table. For example Create table Scores as (Select student.fname,student.lname,studentscores.score from student,studentscores where student.sid=studentscores.sid) In the above example, the results of the join between Student and StudentScores is stored in an another table called Scores. The problem with this approach is if data is changed or added to the student or the StduentScores tables, the Scores table would not to updated. But if you want the Scores table to be updated automatically, you could use Views which you will see in the following sections. In most cases this syntax is used for a quick backup for example, before running a stored procedure, you want to backup the student table into an another table called student_bak, the SQL would be Create table student_bak as(select * from student) Views In the previous section, we have seen how we could use select statements to create other tables, but these tables are not dynamically updated. So an alternative to this is to create a view. A view acts like a table but it does not contain any data. When you query a view, it dynamically fetches the data for itself and then runs your query against that data. For example lets say we have a view called Scores. You could create the view using the following syntax Page 4

Create View Scores as (Select student.fname,student.lname,studentscores.score from student,studentscores where student.sid=studentscores.sid) Once this is created, we can query this view like the following Select * from Scores where Score >100 One advantage of using a view is that if there are any changes to either the Student table or the Scores table, the data is up to date when you query the Scores View. Also views are used to protect some columns from certain users. For example a DBA might want a certain user to see only certain attributes in a table. He could create a view with those attributes and then give permission to the user to that view. This will prevent the user to see all the columns in the parent table. Inserting New Data Usually data in tables is inserted by external applications, that connect to the database. But sometimes you might want to pre populate a table with data. The easiest way to do this in SQL is by using INSERT statements. A simple insert statement would look something like this Insert into Student values( 1111111, John, Smith, jsmith@hotmail.com ); Notice I am enclosing all the fields with single quotes, that is because all the fields in the student table are of type character. But if there were a field of type number you should not enclose that in quotes. In the above statement I am assuming the order in which the columns are present in the database(meaning SID,FIRSTNAME,LASTNAME,EMAILADDRESS), but this might not be the case, so a better way to do the above statement would be Insert into Student (SID,firstname,lastname,emailaddress)values( 1111111, John, Smith, j smith@hotmail.com ); This will make sure, proper data is being inserted into the proper columns in the database.also by using this technique you need not enter all the columns in the database. Insert into Student (SID,firstname,lastname)values( 1111111, John, Smith ); Page 5

By executing the above statement you will create a record but the email field would be null. Also many people forget to put the keyword values when writing insert statements. So if SQL Query generates an error when performing an INSERT see if you have the values keyword first. Updating existing data You might need to update some data in the database. You could accomplish this task by using UPDATE statements. Let say we want to make all the email addresses in our database null, then the corresponding SQL statement would look like this. Update Student set EmailAddress=null Notice the Set keyword in the above statement. Now lets say we want to change the last name and also email address for the student with SID= 1111111111 Update Student set LastName= Doe, EmaiAddress= jdoe@liu.edu where SID= 111111111 So basically you could use the same where clause syntax as in SELECT statements to do updates also. Page 6