sql, databases, etc2

sql, databases, etc2 - Databases, SQL, & Etc By:...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: Databases, SQL, & Etc By: Julia Tartakovsky Acknowledgement (for help with the J# code connecting to an Oracle DB): Yosef Lifshits Database Management System (DBMS) A DBMS is: A collection of interrelated data (a database), and A set of programs to access the data DBMS provides an environment that is both convenient and efficient to use. Database Applications: Banking: all transactions Airlines: reservations, schedules Universities: registration, grades Sales: customers, products, purchases Manufacturing: production, inventory, orders, supply chain Human resources: employee records, salaries, tax deductions Purpose of Database System In the early days, database applications were built on top of file systems We are managing data in this way even today E.g. using Windows Explorer to find your files Drawbacks of using file systems to store data: Data redundancy and inconsistency Multiple file formats, duplication of information in different files Difficulty in accessing data Need to write a new program to carry out each new task Data isolation -- multiple files and formats Integrity problems Integrity constraints (e.g. account balance > 0) become part of program code Hard to add new constraints or change existing ones Purpose of Database Systems (Cont.) Drawbacks of using file systems (cont.) Atomicity of updates Failures may leave database in an inconsistent state with partial updates carried out E.g. transfer of funds from one account to another should either complete or not happen at all Concurrent access by multiple users Concurrent accessed needed for performance Uncontrolled concurrent accesses can lead to inconsistencies E.g. two people reading a balance and updating it at the same time Security problems Database systems offer solutions to all the above problems Application Architectures Two-tier architecture: E.g. client programs using ODBC/JDBC to communicate with a database Three-tier architecture: E.g. web-based applications, and applications built using "middleware" Levels of Abstraction Physical level describes how a record (e.g., customer) is stored. Logical level: describes data stored in database, and the relationships among the data. type customer = record name : string; street : string; city : integer; end; View level: application programs hide details of data types. Views can also hide information (e.g., salary) for security purposes. View of Data An architecture for a database system Instances and Schemas Analogous to types and variables in programming languages Schema the logical structure of the database e.g., the database consists of information about a set of customers and accounts and the relationship between them Analogous to type information of a variable in a program Physical schema: database design at the physical level Logical schema: database design at the logical level Instance the actual content of the database at a particular point in time Analogous to the value of a variable Physical Data Independence the ability to modify the physical schema without changing the logical schema Applications depend on the logical schema In general, the interfaces between various levels and components should be well defined so that changes in some parts do not seriously influence others. Data Models A collection of conceptual tools for describing data data relationships data semantics data constraints Entity-Relationship model Relational model Other models: object-oriented model Object-relational model semi-structured data models, XML Entity-Relationship Model Example of schema in the entity-relationship model: Entity Relationship Model (Cont.) E-R model of real world Entities (objects) E.g. customers, accounts Relationships between entities E.g. Account A-101 is held by customer Johnson Relationship set depositor associates customers with accounts Widely used for database design Database design in E-R model usually converted to design in the relational model (coming up next) which is used for storage and processing Relational Model A collection of tables Example of tabular data in the relational model Customer-id 192-83-7465 019-28-3746 192-83-7465 321-12-3123 019-28-3746 Customername Johnson Smith Johnson Jones Smith Customerstreet Alma North Alma Main North Customercity Palo Alto Rye Palo Alto Harrison Rye Attributes Accountnumber A-101 A-215 A-201 A-217 A-201 A Sample Relational Database What is SQL? SQL (pronounced "ess-que-el") stands for Structured Query Language. SQL is used to communicate with a database. SQL statements are used to perform tasks such as: update data on a database retrieve data from a database What is SQL? (cont.) Relational database management systems that use SQL: Oracle Sybase Microsoft SQL Server Access Ingres Standard SQL commands: "Select" "Insert" "Update" "Delete" "Create" "Drop" SQL SQL: widely used non-procedural language E.g. find the name of the customer with customer-id 192-83-7465 select customer.customer-name from customer where customer.customer-id = `192-83-7465' E.g. find the balances of all accounts held by the customer with customer-id 192-83-7465 select account.balance from depositor, account where depositor.customer-id = `192-83-7465' and depositor.account-number = account.account-number SELECT For more examples and an interactive environment, go to: http://sqlcourse.com/select.html SELECT FROM WHERE CUSTOMER customer id 1 2 3 4 5 name John Smith Joan Bobby Shirley birth year 1975 1955 1980 1976 1974 address Kowloon Kowloon customer_id, name CUSTOMER birth_year>=1975 RESULT customer id 1 3 4 name John Joan Bobby Hong Kong Hong Kong Hong Kong SELECT with Distinct Eliminate identical records. CUSTOMER customer id 1 2 3 4 5 name John Smith Joan Bobby Shirley birth year 1975 1955 1980 1976 1974 address Kowloon Kowloon Hong Kong Hong Kong Hong Kong RESULT SELECT FROM address CUSTOMER address Kowloon Kowloon Hong Kong Hong Kong Hong Kong SELECT distinct address CUSTOMER FROM RESULT address Kowloon Hong Kong Aggregate with Distinct CUSTOMER customer id 1 2 3 4 5 name John Smith Joan Bobby Shirley birth year 1975 1955 1980 1976 1974 address Kowloon Kowloon Hong Kong Hong Kong Hong Kong SELECT FROM count(address) CUSTOMER ANSWER: 5 SELECT FROM count(distinct address) CUSTOMER ANSWER: 2 For more examples and an interactive environment, go to: http://sqlcourse2.com/agg_functions.html Group-by Grouping tuples with identical attributes. ACCOUNT account id customer id A1 A2 A3 A4 A5 1 1 2 3 3 type saving check saving saving check balance 20k 5k 35k 100k 30k RESULT - GROUP BY customer_id account id customer id A1 A2 1 1 type saving check type saving type saving check balance 20k 5k balance 35k balance 100k 30k account id customer id A3 2 account id customer id A4 A5 3 3 For more examples and an interactive environment, go to: http://sqlcourse2.com/groupby.html Summarized Information by Groups SELECT customer_id, COUNT(*) GROUP BY customer_id FROM ACCOUNT type account id customer id GROUP BY customer_id A1 A2 1 1 saving check type saving type saving check balance 20k 5k balance 35k balance 100k 30k account id customer id A3 RESULT customer id 1 2 3 COUNT 2 1 2 2 account id customer id A4 A5 3 3 Group by With "having" Cutting Un-wanted Groups After Group by ACCOUNT SELECT type FROM ACCOUNT GROUP BY type HAVING COUNT(*)>=2 For more examples and an interactive environment, go to: http://sqlcourse2.com/having.html account id customer id A1 A2 A3 A4 A5 1 1 2 3 3 type saving check saving saving check balance 20k 5k 35k 100k 30k Join CUSTOMER customer id name John Smith Joan A1 A2 A3 A4 ACCOUNT account id customer id balance 1 1 2 3 20k 5k 35k 100k SELECT FROM WHERE * CUSTOMER, ACCOUNT CUSTOMER.customer_id = ACCOUNT.customer_id 1 2 3 The result table removes meaningless tuples from the cartesian product. JOIN RESULT CUSTOMER customer id 1 1 2 3 name John John Smith Joan ACCOUNT account id customer id balance A1 A2 A3 A4 1 1 2 3 20k 5k 35k 100k Join With Group By and Having JOIN RESULT SELECT FROM WHERE * CUSTOMER, ACCOUNT CUSTOMER.customer_id = ACCOUNT.customer_id CUSTOMER customer id 1 1 2 name John John Smith Joan ACCOUNT account id customer id balance A1 A2 A3 A4 1 1 2 3 20k 5k 35k 100k CUSTOMER.name, sum(ACCOUNT.balance) FROM CUSTOMER, ACCOUNT WHERE CUSTOMER.customer_id = ACCOUNT.customer_id GROUP BY CUSTOMER.name HAVING COUNT(*)=2 SELECT 3 CUSTOMER ACCOUNT name John John name Smith name balance 20k 5k balance 35k balance 100k JOIN RESULT name John SUM 25k QUESTION: What is the meaning of this query? Joan CREATE Table CREATE TABLE table-name (attr1 attr-type PRIMARYKEY, attr2 attr-type,...,attrN attr-type); Adds a new table with the specified attributes (and types) to the database. For more examples and an interactive environment, go to: http://sqlcourse .com/create.html Access Data Types Numeric (1, 2, 4, 8 bytes, fixed or float) Text (255 max) Memo (64000 max) Date/Time (8 bytes) Currency (8 bytes, 15 digits + 4 digits decimal) Autonumber (4 bytes) Yes/No (1 bit) OLE (limited only by disk space) Hyperlinks (up to 64000 chars) Byte Access Numeric Types Stores numbers from 0 to 255 (no fractions). 1 byte Integer Long Integer (Default) Single Stores numbers from 32,768 to 32,767 (no fractions) 2 bytes Stores numbers from 2,147,483,648 to 2,147,483,647 (no fractions). 4 bytes Stores numbers from -3.402823E38 to 1.401298E45 for negative values and from 1.401298E45 to 3.402823E38 for positive values. 4 bytes Stores numbers from 1.79769313486231E308 to 4.94065645841247E324 for negative values and from 1.79769313486231E308 to 4.94065645841247E324 for positive values. 15 8 bytes Globally unique identifier (GUID) N/A 16 bytes Double Replication ID Oracle Data Types CHAR (size) -- max 2000 VARCHAR2(size) -- up to 4000 DATE DECIMAL, FLOAT, INTEGER, INTEGER(s), SMALLINT, NUMBER, NUMBER(size,d) All numbers internally in same format... up to 2 Gb -- only one per table LONG, LONG RAW, LONG VARCHAR BLOB, CLOB, NCLOB -- up to 4 Gb BFILE -- file pointer to binary OS file Creating a New Table from Existing Tables Syntax: SELECT [DISTINCT] attr1, attr2,..., attr3 INTO newtablename FROM rel1 r1, rel2 r2,... rel3 r3 WHERE condition1 {AND | OR} condition2 ORDER BY attr1 [DESC], attr3 [DESC] ALTER Table ALTER TABLE table-name ADD COLUMN attr1 attr-type; ... DROP COLUMN attr1; Adds a new column to an existing database table. INSERT INSERT INTO table-name (attr1, attr4, attr5,..., attrK) VALUES ("val1", val4, val5,..., "valK"); Adds a new row(s) to a table. INSERT INTO table-name (attr1, attr4, attr5,..., attrK) VALUES SELECT ... For more examples and an interactive environment, go to: http://sqlcourse .com/insert.html DELETE DELETE FROM table-name WHERE <where clause>; Removes rows from a table. For more examples and an interactive environment, go to: http://sqlcourse .com/delete.html UPDATE UPDATE tablename SET attr1=newval, attr2 = newval2 WHERE <where clause>; changes values in existing rows in a table (those that match the WHERE clause). For more examples and an interactive environment, go to: http://sqlcourse .com/update.html DROP Table DROP TABLE tablename; Removes a table from the database. For more examples and an interactive environment, go to: http://sqlcourse.com/drop.html J# Source Code Connecting to an Oracle DB package juliadb1; import System.Drawing.*; import System.Collections.*; import System.ComponentModel.*; import System.Windows.Forms.*; import System.Data.*; // ODP.NET Oracle managed provider /** * Summary description for Form1. */ public class Form1 extends System.Windows.Forms.Form { private System.Windows.Forms.Button button1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; /** * Required designer variable. */ private System.ComponentModel.Container components = null; public Form1() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // Microsoft Word Document } /** * Clean up any resources being used. */ protected void Dispose(boolean disposing) { if (disposing) { if (components != null) { components.Dispose(); } } super.Dispose(disposing); } #region Windows Form Designer generated code /** * Required method for Designer support - do not modify * the contents of this method with the code editor. */ private void InitializeComponent() { Screenshot of J# Program Output Questions? For a neat SQL tutorial and an interactive environment, go to: http://sqlcourse2.com/intro2.html ...
View Full Document

Ask a homework question - tutors are online