2/3/04 Doc 7 SQL Part 1 slide # 1



Similar documents
A Brief Introduction to MySQL

How To Create A Table In Sql (Ahem)

sqlite driver manual

4 Logical Design : RDM Schema Definition with SQL / DDL

6 CHAPTER. Relational Database Management Systems and SQL Chapter Objectives In this chapter you will learn the following:

Database Migration from MySQL to RDM Server

!"# $ %& '( ! %& $ ' &)* + ! * $, $ (, ( '! -,) (# *&23. mysql> select * from from clienti;

Financial Data Access with SQL, Excel & VBA

Database Design and Programming

Specifications of Paradox for Windows

Information Technology NVEQ Level 2 Class X IT207-NQ2012-Database Development (Basic) Student s Handbook

CSC 443 Data Base Management Systems. Basic SQL

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

B.1 Database Design and Definition

SQL. Short introduction

Linas Virbalas Continuent, Inc.

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

Using SQL Server Management Studio

Databases: MySQL Introduction

Database Administration with MySQL

MS ACCESS DATABASE DATA TYPES

Firebird. Embedded SQL Guide for RM/Cobol

Information Systems SQL. Nikolaj Popov

Oracle Database 10g Express

Extracting META information from Interbase/Firebird SQL (INFORMATION_SCHEMA)

SQL Server An Overview

Apache Cassandra Query Language (CQL)

ERserver. DB2 Universal Database for iseries SQL Programming with Host Languages. iseries. Version 5

$%% ",-.,/ B + &! '() E F % 6: !!!"#$ " '*( ) > & *!!! "& +,!,, mysql [-h host] [-u user] [-p[pass]] % ' ?!!!

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

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

Package sjdbc. R topics documented: February 20, 2015

Relational Databases. Christopher Simpkins

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

Advance DBMS. Structured Query Language (SQL)

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

3.GETTING STARTED WITH ORACLE8i

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

Guide to the Superbase. ODBC Driver. By Superbase Developers plc

MYSQL DATABASE ACCESS WITH PHP

MySQL 5.1 INTRODUCTION 5.2 TUTORIAL

Oracle Database 10g: Introduction to SQL

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

How Strings are Stored. Searching Text. Setting. ANSI_PADDING Setting

- Suresh Khanal. Microsoft Excel Short Questions and Answers 1

Chapter 6: Physical Database Design and Performance. Database Development Process. Physical Design Process. Physical Database Design

Comparison of Open Source RDBMS

SQL 2: GETTING INFORMATION INTO A DATABASE. MIS2502 Data Analytics

Once the schema has been designed, it can be implemented in the RDBMS.

Teradata SQL Assistant Version 13.0 (.Net) Enhancements and Differences. Mike Dempsey

SQL: joins. Practices. Recap: the SQL Select Command. Recap: Tables for Plug-in Cars

The release notes provide details of enhancements and features in Cloudera ODBC Driver for Impala , as well as the version history.

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

Setting Up ALERE with Client/Server Data

Programming with SQL

SQL Server for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach

Choosing a Data Model for Your Database

Using the SQL Procedure

C++ Wrapper Library for Firebird Embedded SQL

Advanced SQL. Jim Mason. Web solutions for iseries engineer, build, deploy, support, train

Introduction to Microsoft Jet SQL

Creating Database Tables in Microsoft SQL Server

CSE 530A Database Management Systems. Introduction. Washington University Fall 2013

VBA and Databases (see Chapter 14 )

"SQL Database Professional " module PRINTED MANUAL

Title. Syntax. stata.com. odbc Load, write, or view data from ODBC sources. List ODBC sources to which Stata can connect odbc list

MySQL for Beginners Ed 3

4 Simple Database Features

Oracle Database 12c: Introduction to SQL Ed 1.1

Database: SQL, MySQL

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

Services. Relational. Databases & JDBC. Today. Relational. Databases SQL JDBC. Next Time. Services. Relational. Databases & JDBC. Today.

Microsoft SQL Server to Infobright Database Migration Guide

Mini User's Guide for SQL*Plus T. J. Teorey

Working with DB2 UDB objects

A list of data types appears at the bottom of this document. String datetimestamp = new java.sql.timestamp(system.currenttimemillis()).

Facebook Twitter YouTube Google Plus Website

The Relational Model. Why Study the Relational Model?

WHY DO YOU NEED A DATABASE? USE A DATABASE IF USE A SPREADSHEET IF

EECS 647: Introduction to Database Systems

Language Reference Guide

Assignment 3 Version 2.0 Reactive NoSQL Due April 13

DbSchema Tutorial with Introduction in SQL Databases

not at all a manual simply a quick how-to-do guide

database abstraction layer database abstraction layers in PHP Lukas Smith BackendMedia

Introduction to Database. Systems HANS- PETTER HALVORSEN,

Database Query 1: SQL Basics

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

Porting from Oracle to PostgreSQL

FileMaker 13. SQL Reference

Structured Query Language (SQL)

Database migration. from Sybase ASE to PostgreSQL. Achim Eisele and Jens Wilke. 1&1 Internet AG

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

Teach Yourself InterBase

Introduction to SQL for Data Scientists

Transcription:

2/3/04 Doc 7 SQL Part 1 slide # 1 CS 580 Client-Server Programming Spring Semester, 2004 Doc 7 SQL Part 1 Contents Database... 2 Types of Databases... 6 Relational, Object-Oriented Databases and SQL... 7 Names... 12 Data Types... 13 Numeric Data Types... 15 String Types... 16 Date & Time Types - PostgreSQL... 17 Common SQL Statements... 20 CREATE DATABASE... 22 USE... 23 CREATE table... 24 Select... 25 Insert... 26 Update... 28 Alter Table... 29 Drop Table... 31 Drop Database... 32 References MySQL On-line Manual http://www.mysql.com/doc/en/reference.html MySQL, DuBois, New Riders, 2000 PostgreSQL Developer s Handbook, Geschwinde, Schönig, Sams, 2002 PostgreSQL Interactive Documentation http://www.postgresql.org/idocs/ PostgreSQL Technical Documentation Web site, http://techdocs.postgresql.org/ Andrew Scherpbier s CS580 Lecture notes http://www.eli.sdsu.edu/courses/spring97/cs596/notes/databases/databases.html Copyright, All rights reserved. 2004 SDSU & Roger Whitney, 5500 Campanile Drive, San Diego, CA 92182-7700 USA. OpenContent (http://www.opencontent.org/opl.shtml) license defines the copyright on this document.

2/3/04 Doc 7 SQL Part 1 slide # 2 Database Most servers will use some sort of database. Jargon

2/3/04 Doc 7 SQL Part 1 slide # 3 What is a database? A database holds information and provides for a mechanism to access this information. Examples of some common (electronic) databases: Unix password file IRS records system Rolodex(TM) Computer file system Library (object files) Student grades Telephone directory

2/3/04 Doc 7 SQL Part 1 slide # 4 Jargon Sometimes database means a program for managing data Oracle Corporation is a database company. MS Access is database. Sometimes database means a collection of data I keep a database of my CD collection on 3 by 5 cards Sometimes database means a set of tables, indexes, and views My program needs to connect to the Airline Reservation database, which uses Oracle

2/3/04 Doc 7 SQL Part 1 slide # 5 Some Reasons for Using a Database Persistence of data Sharing of data between programs Handle concurrent requests for data access Transactions that can be rolled back Report generation

2/3/04 Doc 7 SQL Part 1 slide # 6 Types of Databases Relational Data is stored in tables Object-Oriented Tables can be subclassed Programmer can define methods on tables Object Objects are stored in the database

2/3/04 Doc 7 SQL Part 1 slide # 7 Relational, Object-Oriented Databases and SQL Database consists of a number of tables Table is a collection of records Each Column of data has a type +----------------------+----------------------+------------+----------+ firstname lastname phone code +----------------------+----------------------+------------+----------+ John Smith 555-9876 2000 Ben Oker 555-1212 9500 Mary Jones 555-3412 9900 +----------------------+----------------------+------------+----------+ Use Structured query language (SQL) to access data

2/3/04 Doc 7 SQL Part 1 slide # 8 Oracle DB2 SQL Server Access Informix Ingres InterBase Sybase FileMaker Pro FoxPro Paradox dbase Open Source Databases MySQL PostgresSQL Some Available Databases

2/3/04 Doc 7 SQL Part 1 slide # 9 SQL History Structured query language (SQL) Dr. E. F. Codd develops relational database model Early 1970's IBM System R relational database Mid 1970's Contained the original SQL language First commercial database - Oracle 1979 SQL was aimed at: Accountants Business people SQL89 Not well followed ANSI X3.135-1989 SQL92 First commonly followed standard ANSI X3.135-1992 SQL2 ISO/IEC 9075-1 through 5 New SQL standard

2/3/04 Doc 7 SQL Part 1 slide # 10 MySQL & PostgreSQL Open source databases http://www.mysql.com/ http://www.postgresql.org/ Above site have free downloads and documentation

2/3/04 Doc 7 SQL Part 1 slide # 11 Can be done with: MySQL Connecting to the Database Mysql command line tool - mysql GUI clients Program If done well are very useful There are many of these GUI Clients MySql web site lists 10 pages of them, see: http://www.mysql.com/portal/software/graphing/index.html I know several people that use DbVisualizer, DbVisualizer if Java based so runs on may platforms http://www.dbvis.com/products/dbvis/

2/3/04 Doc 7 SQL Part 1 slide # 12 Names Databases, tables columns & indexes have names Alphanumeric characters '_' '$' Legal Characters Names can start with: Letter Underscore Letter with diacritical marks and some non-latin letters Name length 63 characters default in PostgreSQL 64 characters - MySQL Names are not case sensitive

2/3/04 Doc 7 SQL Part 1 slide # 13 Data Types Numeric Values Integer - decimal or hex Floating-point - scientific & 12.1234 String Values this is a string PostgreSQL this is a string this is also a string MySQL Sequence Meaning \' Single quote \b Backspace \n Newline \r Tab \\ Backslash \xxxx Character were xxxx is the octal of ASCII code (PostgreSQL) Including a quote character in a string Double quote the character 'Don''t do it' Escape the quote character with a backslash 'Don\'t do it'

2/3/04 Doc 7 SQL Part 1 slide # 14 Comments -- this is a comment in MySQL and PostgreSQL /* this is also a comment in MySQL and PostgreSQL */ # this is a comment in MySQL

2/3/04 Doc 7 SQL Part 1 slide # 15 Numeric Data Types Type name Description Range smallint Fixed-precision -32768 to +32767 integer Usual choice for -2147483648 to +2147483647 fixed-precision bigint Very large range fixed-precision -9223372036854775808 to 9223372036854775807 decimal user-specified no limit precision, exact numeric user-specified no limit precision, exact real variable-precision, 6 decimal digits precision inexact double variable-precision, 15 decimal digits precision precision inexact serial autoincrementing integer 1 to 2147483647 Numeric(10, 2) defines a number with maximum of 10 digits with 2 of the 10 to the right of the decimal point 12345678.91 decimal and numeric are different names for the same type

2/3/04 Doc 7 SQL Part 1 slide # 16 String Types Type char(n) varchar(n) text bytea (PostgreSQL) blob (MySQL) Description Fixed-length blank padded Variable-length with limit Variable unlimited length Variable (not specifically limited) length binary string Variable (not specifically limited) length binary string CHAR & VARCHAR are the most common string types CHAR is fixed-width Shorter strings are padded TEXT can be any size PostgreSQL limits a string to 1GB in storage space MySQL limits CHAR and VARCHAR to 255 characters

2/3/04 Doc 7 SQL Part 1 slide # 17 Date & Time Types - PostgreSQL Type timestamp [(p)] without time zone timestamp [ (p) ] [ with time zone ] interval [ (p) ] date time [ (p) ] [ without time zone ] time [ (p) ] with time zone Description both date and time both date and time for time intervals dates only times of day only times of day only (p) indicates optional number of fractional digits retained in the seconds field

2/3/04 Doc 7 SQL Part 1 slide # 18 Date Formats - PostgreSQL Example Description January 8, 1999 Unambiguous 1999-01-08 ISO-8601 format, preferred 1/8/1999 U.S.; read as August 1 in European mode 8/1/1999 European; read as August 1 in U.S. mode 1/18/1999 U.S.; read as January 18 in any mode 19990108 ISO-8601 year, month, day 990108 ISO-8601 year, month, day 1999.008 Year and day of year 99008 Year and day of year J2451187 Julian day January 8, 99 BC Year 99 before the Common Era Setting the Date Format SET DateStyle TO US SET DateStyle TO NonEuropean Sets date format to month day year SET DateStyle TO European Sets date format to day month year Default is ISO style

2/3/04 Doc 7 SQL Part 1 slide # 19 Dates MySQL DATETIME YYYY-MM-DD HH:MM:SS format DATE YYYY-MM-DD format TIMESTAMP Changed in MySQL 4.1 Basically now is same as DATETIME

2/3/04 Doc 7 SQL Part 1 slide # 20 Common SQL Statements SELECT INSERT UPDATE DELETE CREATE TABLE DROP TABLE ALTER TABLE CREATE INDEX DROP INDEX CREATE VIEW DROP VIEW Retrieves data from table(s) Adds row(s) to a table Changes field(s) in record(s) Removes row(s) from a table Data Definition Define a table and its columns(fields) Deletes a table Adds a new column, add/drop primary key Create an index Deletes an index Define a logical table from other table(s)/view(s) Deletes a view SQL is not case sensitive

2/3/04 Doc 7 SQL Part 1 slide # 21 Examples That Follow Will use mysql command line tool Used the command mysql -h host -u user -p to conntect to the database, where host and user are given the correct value On rohan the full name of command is: /opt/local/mysql/bin/mysql

2/3/04 Doc 7 SQL Part 1 slide # 22 CREATE DATABASE General Form CREATE DATABASE [IF NOT EXISTS] db_name [create_specification [, create_specification]...] create_specification: [DEFAULT] CHARACTER SET charset_name [DEFAULT] COLLATE collation_name Example mysql> create database lectureexamples; Query OK, 1 row affected (0.00 sec)

2/3/04 Doc 7 SQL Part 1 slide # 23 USE Sets a default database for subsequent queries USE db_name mysql> use lectureexamples; Database changed General Form Example

2/3/04 Doc 7 SQL Part 1 slide # 24 Creates a table. CREATE table General Form CREATE TABLE table_name ( col_name col_type [ NOT NULL PRIMARY KEY] [, col_name col_type [ NOT NULL PRIMARY KEY]]* ) Example mysql> CREATE TABLE students ( firstname CHAR(20) NOT NULL, lastname CHAR(20), phone CHAR(10), code INTEGER ); mysql> CREATE TABLE codes ( code INTEGER, name CHAR(20) );

2/3/04 Doc 7 SQL Part 1 slide # 25 Select Gets data from one or more tables General Form SELECT [STRAIGHT_JOIN] [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT] [SQL_CACHE SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS] [HIGH_PRIORITY] [DISTINCT DISTINCTROW ALL] select_expression,... [INTO {OUTFILE DUMPFILE} 'file_name' export_options] [FROM table_references [WHERE where_definition] [GROUP BY {unsigned_integer col_name formula} [ASC DESC],... [WITH ROLLUP]] [HAVING where_definition] [ORDER BY {unsigned_integer col_name formula} [ASC DESC],...] [LIMIT [offset,] row_count row_count OFFSET offset] [PROCEDURE procedure_name(argument_list)] [FOR UPDATE LOCK IN SHARE MODE]] mysql> SELECT * FROM students; Empty set (0.00 sec) Example

2/3/04 Doc 7 SQL Part 1 slide # 26 Add data to a table Insert General Form INSERT [LOW_PRIORITY DELAYED] [IGNORE] [INTO] tbl_name [(col_name,...)] VALUES ((expression DEFAULT),...),(...),... [ ON DUPLICATE KEY UPDATE col_name=expression,... ] Examples mysql> INSERT INTO students (firstname, lastname, phone, code) VALUES ('Roger', 'Whitney', '594-3535', 2000 ); mysql> INSERT INTO codes (code, name) VALUES (2000, 'marginal' ); mysql> SELECT * FROM students; +-----------+----------+----------+------+ firstname lastname phone code +-----------+----------+----------+------+ Roger Whitney 594-3535 2000 +-----------+----------+----------+------+ 1 row in set (0.01 sec)

2/3/04 Doc 7 SQL Part 1 slide # 27 More Select Examples mysql> SELECT firstname, phone FROM students; +-----------+----------+ firstname phone +-----------+----------+ Roger 594-3535 +-----------+----------+ 1 row in set (0.00 sec) mysql> SELECT lastname, name FROM students, codes WHERE students.code = codes.code; +----------+----------+ lastname name +----------+----------+ Whitney marginal +----------+----------+ 1 row in set (0.00 sec) mysql> SELECT students.lastname, codes.name FROM students, codes WHERE students.code = codes.code; +----------+----------+ lastname name +----------+----------+ Whitney marginal +----------+----------+ 1 row in set (0.00 sec)

2/3/04 Doc 7 SQL Part 1 slide # 28 Update Modify existing data in a database General Form UPDATE [LOW_PRIORITY] [IGNORE] tbl_name [, tbl_name...] SET col_name1=expr1 [, col_name2=expr2...] [WHERE where_definition] mysql> UPDATE students SET firstname='sam' WHERE lastname='whitney'; Example Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0

2/3/04 Doc 7 SQL Part 1 slide # 29 Alter Table Modify the table structure add/delete columns, change column type General Form ALTER [IGNORE] TABLE tbl_name alter_specification [, alter_specification]... alter_specification: ADD [COLUMN] create_definition [FIRST AFTER column_name ] ADD [COLUMN] (create_definition, create_definition,...) ADD INDEX [index_name] [index_type] (index_col_name,...) ADD [CONSTRAINT [symbol]] PRIMARY KEY [index_type] (index_col_name,...) ADD [CONSTRAINT [symbol]] UNIQUE [index_name] [index_type] (index_col_name,...) ADD [CONSTRAINT [symbol]] FOREIGN KEY [index_name] (index_col_name,...) [reference_definition] ALTER [COLUMN] col_name {SET DEFAULT literal DROP DEFAULT} CHANGE [COLUMN] old_col_name create_definition [FIRST AFTER column_name] MODIFY [COLUMN] create_definition [FIRST AFTER column_name] DROP [COLUMN] col_name DROP PRIMARY KEY DROP INDEX index_name DISABLE KEYS ENABLE KEYS RENAME [TO] new_tbl_name ORDER BY col CHARACTER SET character_set_name [COLLATE collation_name] table_options

2/3/04 Doc 7 SQL Part 1 slide # 30 Example mysql> ALTER TABLE students ADD column foo CHAR(40); Query OK, 1 row affected (0.03 sec) Records: 1 Duplicates: 0 Warnings: 0

2/3/04 Doc 7 SQL Part 1 slide # 31 Drop Table Remove a table from the database General Form DROP [TEMPORARY] TABLE [IF EXISTS] tbl_name [, tbl_name,...] [RESTRICT CASCADE] Example mysql> DROP TABLE students; Query OK, 0 rows affected (0.01 sec)

2/3/04 Doc 7 SQL Part 1 slide # 32 Drop Database Removes a database and all its tables General Form DROP DATABASE [IF EXISTS] db_name Example mysql> DROP DATABASE lectureexamples; Query OK, 0 rows affected (0.00 sec)