How to use SQL to create a database

Similar documents
Introduction to relational databases and MySQL

Chapter 3. Introduction to relational databases and MySQL. 2010, Mike Murach & Associates, Inc. Murach's PHP and MySQL, C3

How to use SQL to work with a MySQL database

Chapter 3 Introduction to relational databases and MySQL

Chapter 11 How to create databases, tables, and indexes

Lecture 5. Monday, September 15, 2014

Chapter 13 : Informatics Practices. Class XI ( As per CBSE Board) SQL Commands. New Syllabus Visit : python.mykvs.in for regular updates

DATABASE MANAGEMENT SYSTEMS

SQL Commands & Mongo DB New Syllabus

Private Institute of Aga NETWORK DATABASE LECTURER NIYAZ M. SALIH

QUETZALANDIA.COM. 5. Data Manipulation Language

HOW TO CREATE AND MAINTAIN DATABASES AND TABLES. By S. Sabraz Nawaz Senior Lecturer in MIT FMC, SEUSL

Unit 1 - Chapter 4,5

MySQL. Prof.Sushila Aghav

Relational databases and SQL

CSC Web Programming. Introduction to SQL

Unit 27 Web Server Scripting Extended Diploma in ICT

Lecture 07. Spring 2018 Borough of Manhattan Community College

MySQL by Examples for Beginners

Introduction to SQL. IT 5101 Introduction to Database Systems. J.G. Zheng Fall 2011

CS 327E Lecture 2. Shirley Cohen. January 27, 2016

Lab # 2 Hands-On. DDL Basic SQL Statements Institute of Computer Science, University of Tartu, Estonia

Chapter 1 An introduction to relational databases and SQL

Database Foundations. 6-3 Data Definition Language (DDL) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

Chapter-14 SQL COMMANDS

STRUCTURED QUERY LANGUAGE (SQL)

SQL Fundamentals. Chapter 3. Class 03: SQL Fundamentals 1

Database Systems. phpmyadmin Tutorial

IT360: Applied Database Systems. SQL: Structured Query Language DDL and DML (w/o SELECT) (Chapter 7 in Kroenke) SQL: Data Definition Language

Short List of MySQL Commands

User's Guide c-treeace SQL Explorer

What is MySQL? [Document provides the fundamental operations of PHP-MySQL connectivity]

tablename ORDER BY column ASC tablename ORDER BY column DESC sortingorder, } The WHERE and ORDER BY clauses can be combined in one

MySQL Introduction. By Prof. B.A.Khivsara


SELF TEST. List the Capabilities of SQL SELECT Statements

Exam Actual. Higher Quality. Better Service! QUESTION & ANSWER

ASSIGNMENT NO 2. Objectives: To understand and demonstrate DDL statements on various SQL objects

Data Definition Language with mysql. By Kautsar

SQL stands for Structured Query Language. SQL lets you access and manipulate databases

SQL Server 2012 Development Course

CMP-3440 Database Systems

Seminar 3. Stored procedures. Global variables. Dynamic Execution. The OUTPUT clause. Cursors

Structured Query Language (SQL): A Primer on Data Definition Language (DDL)

Course Topics. Microsoft SQL Server. Dr. Shohreh Ajoudanian. 01 Installing MSSQL Server Data types

Lab # 4 Hands-On. DDL and DML Advance SQL Statements Institute of Computer Science, University of Tartu, Estonia

SQL Data Definition and Data Manipulation Languages (DDL and DML)

Mysql interview questions and answers

Oracle EXAM - 1Z Oracle Database SQL Expert. Buy Full Product.

Relational Database Development

Introduction to SQL on GRAHAM ED ARMSTRONG SHARCNET AUGUST 2018

MIS2502: Data Analytics SQL Getting Information Out of a Database Part 1: Basic Queries

Oracle 1Z Oracle Database 12c SQL. Download Full Version :

CHAPTER. Introduction

Relational Data Structure and Concepts. Structured Query Language (Part 1) The Entity Integrity Rules. Relational Data Structure and Concepts

30. Structured Query Language (SQL)

Question No : 1 Which three possible values can be set for the TIME_ZONE session parameter by using the ALTER SESSION command? (Choose three.

Chapter 4. Basic SQL. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Table Joins and Indexes in SQL

This lab will introduce you to MySQL. Begin by logging into the class web server via SSH Secure Shell Client

MIS2502: Review for Exam 2. JaeHwuen Jung

D B M G. SQL language: basics. Managing tables. Creating a table Modifying table structure Deleting a table The data dictionary Data integrity

Working with Databases and Java

Chapter 9: MySQL for Server-Side Data Storage

Exam code: Exam name: Database Fundamentals. Version 16.0

Today Learning outcomes LO2

Keys are fields in a table which participate in below activities in RDBMS systems:

MySQL 5.0 Certification Study Guide

Professional PHP for working with MySQL

Intro to Database Commands

A Project Report On E-Watch Shopping System

1. Using Bitvise SSH Secure Shell to login to CS Systems Note that if you do not have Bitvise ssh secure shell on your PC, you can download it from

CSC 3300 Homework 3 Security & Languages

Structured Query Language (SQL)

Introduction to Databases. MySQL Syntax Guide: Day 1

Week 11 ~ Chapter 8 MySQL Command Line. PHP and MySQL CIS 86 Mission College

1z Oracle Database SQL Expert

Create Basic Databases and Integrate with a Website Lesson 1

ERD Tutorial: How to Design and Generate SQL Server DB? Written Date : June 19, 2015

Lab # 2. Data Definition Language (DDL) Eng. Alaa O Shama

EE221 Databases Practicals Manual

Exact Numeric Data Types

SQL language. Jaroslav Porubän, Miroslav Biňas, Milan Nosáľ (c)

The M in LAMP: MySQL CSCI 470: Web Science Keith Vertanen Copyright 2014

Simple Quesries in SQL & Table Creation and Data Manipulation

Accessing databases in Java using JDBC

Microsoft MOS- Using Microsoft Office Access Download Full Version :

Oracle Academy Amazing Books Part 1: Building Tables and Adding Constraints

Chapter 1 SQL and Data

MIS2502: Review for Exam 2. Jing Gong

CHAPTER: 4 ADVANCE SQL: SQL PERFORMANCE TUNING (12 Marks)

COSC344 Database Theory and Applications. Lecture 5 SQL - Data Definition Language. COSC344 Lecture 5 1

Lab # 4. Data Definition Language (DDL)

1z0-047 Exam Questions Demo Oracle. Exam Questions 1z Oracle Database SQL Expert.

L e a r n S q l select where

Assignment Grading Rubric

Lecture7: SQL Overview, Oracle Data Type, DDL and Constraints Part #2

CHAPTER4 CONSTRAINTS

The Structured Query Language Get Started

KillTest. 半年免费更新服务

Transcription:

Chapter 17 How to use SQL to create a database How to create a database CREATE DATABASE my_guitar_shop2; How to create a database only if it does not exist CREATE DATABASE IF NOT EXISTS my_guitar_shop2; How to select a database USE my_guitar_shop2; How to drop a database DROP DATABASE my_guitar_shop2; How to drop a database only if it exists DROP DATABASE IF EXISTS my_guitar_shop2; 2017, Mike Murach & Associates, Inc. C17, Slide 1 2017, Mike Murach & Associates, Inc. C17, Slide 4 Objectives Applied 1. Given the design for a database, create a SQL script that will create the database, including all tables, primary keys, foreign key constraints, and indexes. 2. Use SQL statements to create users and assign privileges to the users. 3. Load data into a database table from a text file. 4. Dump a database to a SQL script. Common numeric data types INT[size)] TINYINT[size)] DECIMAL[p[,s])] Common string data types VARCHARsize) CHAR[size)] TEXT Common date and time data types DATE TIME DATETIME 2017, Mike Murach & Associates, Inc. C17, Slide 2 2017, Mike Murach & Associates, Inc. C17, Slide 5 Objectives continued) Knowledge 1. Describe the use of the DDL statements for creating, altering, and dropping databases, tables, and indexes. 2. Describe the column definitions for a table in terms of data types and these attributes: unique, not null, default, primary key, autoincrement, and references. Also, describe a table-level definition for a primary key and a foreign key constraint. 3. Describe the use of the DDL statements for creating, renaming, and dropping users and for assigning and revoking privileges. 4. Describe the process of loading data from a text file into a table, and the process of dumping a database to a SQL script. 5. Describe the use of a script for creating a database. The syntax of the CREATE TABLE statement CREATE TABLE [IF NOT EXISTS] tablename columnname1 datatype [columnattributes][, columnname2 datatype [columnattributes]][, columnname3 datatype [columnattributes]]... ) Three common column attributes UNIQUE NOT NULL DEFAULT default_value 2017, Mike Murach & Associates, Inc. C17, Slide 3 2017, Mike Murach & Associates, Inc. C17, Slide 6 1

A table without column attributes CREATE TABLE customers customerid INT, firstname VARCHAR60), lastname VARCHAR60) A table with column attributes CREATE TABLE customers customerid INT NOT NULL UNIQUE, firstname VARCHAR60) NOT NULL, lastname VARCHAR60) NOT NULL A table with a two-column primary key CREATE TABLE orderitems orderid INT NOT NULL, productid INT NOT NULL, itemprice DECIMAL10,2) NOT NULL, discountamount DECIMAL10,2) NOT NULL, quantity INT NOT NULL, PRIMARY KEY orderid, productid) 2017, Mike Murach & Associates, Inc. C17, Slide 7 2017, Mike Murach & Associates, Inc. C17, Slide 10 Another table with column attributes CREATE TABLE orders orderid INT NOT NULL UNIQUE, ordernumber VARCHAR50) NOT NULL, orderdate DATE NOT NULL, ordertotal DECIMAL9,2) NOT NULL, paymenttotal DECIMAL9,2) DEFAULT 0 Three attributes for working with a foreign key CONSTRAINT FOREIGN KEY REFERENCES A table with a column-level foreign key constraint CREATE TABLE orders orderid INT PRIMARY KEY, customerid INT NOT NULL REFERENCES customers customerid), orderdate DATETIME NOT NULL ) 2017, Mike Murach & Associates, Inc. C17, Slide 8 2017, Mike Murach & Associates, Inc. C17, Slide 11 Two column attributes for working with a primary key PRIMARY KEY AUTO_INCREMENT A table with a column-level primary key CREATE TABLE customers customerid INT NOT NULL PRIMARY KEY emailaddress VARCHAR255) NOT NULL A table with a table-level primary key CREATE TABLE customers AUTO_INCREMENT, UNIQUE customerid INT NOT NULL AUTO_INCREMENT, emailaddress VARCHAR255) NOT NULL UNIQUE, A table with a table-level foreign key constraint CREATE TABLE orders orderid INT PRIMARY KEY, orderdate DATETIME NOT NULL, CONSTRAINT ordersfkcustomers FOREIGN KEY customerid) REFERENCES customers customerid) ) A constraint that uses the ON DELETE clause CONSTRAINT ordersfkcustomers FOREIGN KEY customerid) REFERENCES customers customerid) ON DELETE CASCADE PRIMARY KEY customerid) 2017, Mike Murach & Associates, Inc. C17, Slide 9 2017, Mike Murach & Associates, Inc. C17, Slide 12 2

An insert statement that fails because a related row doesn t exist INSERT INTO orders VALUES 1, 999, '2017-08-03') The response from the system Error Code: 1452. Cannot add or update a child row: a foreign key constraint fails 'ex'.'orders', CONSTRAINT 'ordersfkcustomers' FOREIGN KEY 'customerid') REFERENCES 'customers' 'customerid')) A statement that drops a table DROP TABLE customers; A statement that drops a table if it exists DROP TABLE IF EXISTS customers; Warning You should never drop a table in a production database without first consulting the DBA, but you probably won t have the privileges for doing that. 2017, Mike Murach & Associates, Inc. C17, Slide 13 2017, Mike Murach & Associates, Inc. C17, Slide 16 A statement that renames a table ALTER TABLE products RENAME TO product; A statement that adds a new column at the end of the table ALTER TABLE customers ADD lasttransactiondate DATE; A statement that adds a new column after a specified column ALTER TABLE customers ADD lasttransactiondate DATE AFTER emailaddress; A statement that drops a column ALTER TABLE customers DROP lasttransactiondate; A statement that renames a column ALTER TABLE customers CHANGE emailaddress email VARCHAR255) NOT NULL UNIQUE; The syntax of the CREATE INDEX statement CREATE [UNIQUE] INDEX KEY indexname ON tablename columnname1 [ASC DESC] [, columnname2 [ASC DESC]]...) A statement that Creates an index based on a single column CREATE INDEX customerid ON orders customerid Creates a unique index CREATE UNIQUE INDEX emailaddress ON customers emailaddress Creates an index based on two columns CREATE UNIQUE INDEX customeridordernumber ON orders customerid, ordernumber Creates an index that s sorted in descending order CREATE INDEX ordertotal ON orders ordertotal DESC 2017, Mike Murach & Associates, Inc. C17, Slide 14 2017, Mike Murach & Associates, Inc. C17, Slide 17 A statement that changes a column definition ALTER TABLE customers MODIFY firstname VARCHAR100) NOT NULL A statement that changes a column s data type ALTER TABLE customers MODIFY firstname CHAR100) NOT NULL; A statement that may cause data to be lost ALTER TABLE customers MODIFY firstname VARCHAR8 A statement that sets a column s default value ALTER TABLE customers ALTER firstname SET DEFAULT ''; A statement that drops a column s default value ALTER TABLE customers ALTER firstname DROP DEFAULT; Warning You should never alter a table or other database object in a production database without first consulting the DBA. A CREATE TABLE statement that creates indexes CREATE TABLE customers customerid INT NOT NULL AUTO_INCREMENT, emailaddress VARCHAR255) NOT NULL, firstname VARCHAR60) NOT NULL, PRIMARY KEY customerid), UNIQUE INDEX emailaddress emailaddress), INDEX firstname firstname) A DROP INDEX statement that drops an index DROP INDEX firstname ON customers; 2017, Mike Murach & Associates, Inc. C17, Slide 15 2017, Mike Murach & Associates, Inc. C17, Slide 18 3

Privileges for working with data SELECT INSERT UPDATE DELETE Privileges for modifying the database structure CREATE ALTER DROP INDEX How to create a user from a specific host CREATE USER joel@localhost IDENTIFIED BY 'sesame'; How to create a user from any host CREATE USER dba IDENTIFIED BY 'sesame'; How to rename a user from a specific host RENAME USER joel@localhost TO joelmurach@localhost; How to change a user s password GRANT USAGE ON *.* TO joelmurach@localhost IDENTIFIED BY 'newpassword'; How to drop a user from a specific host DROP USER joelmurach@localhost; How to drop a user from any host DROP USER dba; 2017, Mike Murach & Associates, Inc. C17, Slide 19 2017, Mike Murach & Associates, Inc. C17, Slide 22 Other privileges CREATE USER ALL [PRIVILEGES] GRANT OPTION USAGE The syntax of the GRANT statement GRANT privilegelist ON [dbname.]table TO username1 [IDENTIFIED BY 'password1'] [, username2 [IDENTIFIED BY 'password2']...] [WITH GRANT OPTION] A statement that uses the current database no database name is specified) GRANT SELECT, INSERT, UPDATE, DELETE ON customers TO joel@localhost; 2017, Mike Murach & Associates, Inc. C17, Slide 20 2017, Mike Murach & Associates, Inc. C17, Slide 23 The four privilege levels Level Example Global *.* Database music_db.* Table music_db.products Column listprice) music_db.products A statement that creates a user with no privileges GRANT USAGE ON *.* TO joel@localhost IDENTIFIED BY 'sesame'; A statement that creates a user with database privileges GRANT SELECT, INSERT, UPDATE, DELETE ON my_guitar_shop2.* TO mgs_user@localhost IDENTIFIED BY 'pa55word'; A statement that creates a user with global privileges GRANT ALL ON *.* TO dba IDENTIFIED BY 'supersecret' WITH GRANT OPTION; 2017, Mike Murach & Associates, Inc. C17, Slide 21 2017, Mike Murach & Associates, Inc. C17, Slide 24 4

A statement that grants table privileges to a user GRANT SELECT, INSERT, UPDATE ON my_guitar_shop2.products TO joel@localhost; A statement that grants database privileges to a user GRANT SELECT, INSERT, UPDATE ON my_guitar_shop2.* TO joel@localhost; A statement that grants global privileges to a user GRANT SELECT, INSERT, UPDATE ON *.* TO joel@localhost; A statement that grants column privileges to a user GRANT SELECT productcode, productname, listprice), UPDATE description) ON my_guitar_shop2.products TO joel@localhost A statement that lists all users SELECT User, Host from mysql.user; The result set 2017, Mike Murach & Associates, Inc. C17, Slide 25 2017, Mike Murach & Associates, Inc. C17, Slide 28 The syntax of the REVOKE statement for all privileges REVOKE ALL[ PRIVILEGES], GRANT OPTION FROM user [, user] A statement that revokes all privileges from a user REVOKE ALL, GRANT OPTION FROM dba; A statement that revokes all privileges from multiple users REVOKE ALL, GRANT OPTION FROM dba, joel@localhost; The syntax of the SHOW GRANTS statement SHOW GRANTS [FOR user] A statement that shows the privileges for a user from any host SHOW GRANTS FOR dba; The result set 2017, Mike Murach & Associates, Inc. C17, Slide 26 2017, Mike Murach & Associates, Inc. C17, Slide 29 The syntax of the REVOKE statement for specific privileges REVOKE privilegelist ON [dbname.]table FROM user [, user] A statement that revokes specific privileges from a user REVOKE UPDATE, DELETE ON my_guitar_shop2.customers FROM joel@localhost A statement that shows the privileges for a user from a specific host SHOW GRANTS FOR mgs_user@localhost; The result set A statement that shows the privileges for the current user SHOW GRANTS; 2017, Mike Murach & Associates, Inc. C17, Slide 27 2017, Mike Murach & Associates, Inc. C17, Slide 30 5

The Import tab for a table named products The Export tab for my_guitar_shop2 2017, Mike Murach & Associates, Inc. C17, Slide 31 2017, Mike Murach & Associates, Inc. C17, Slide 34 A tab-delimited text file that s stored in users.txt 1 John Smith jsmith@gmail.com 2 Andrea Steelman andi@murach.com 3 Joel Murach joelmurach@yahoo.com Using phpmyadmin to load data from a text file 1. Start phpmyadmin, select the database, select the table, and click on the Import tab. 2. Select the file to import. 3. Set the options for the import and click the Go button. If you get an error, you can modify the import options and try again. How to use phpmyadmin to dump a database 1. Start phpmyadmin, select the database, and click on the Export tab. 2. Set the options for the SQL script file. 3. Click on the Go button and save the file. How to use the Windows command prompt to dump a database to a SQL script cd \xampp\mysql\bin mysqldump -u root -p my_guitar_shop2 > my_guitar_shop2.sql Enter password: ****** 2017, Mike Murach & Associates, Inc. C17, Slide 32 2017, Mike Murach & Associates, Inc. C17, Slide 35 How to use the Windows command prompt to load data from a text file cd \xampp\mysql\bin mysql -u root -p Enter password: ****** use my_guitar_shop2; load data local infile "c:/murach/products.txt" into table products; exit; The SQL script that creates the my_guitar_shop2 database -- create and select the database DROP DATABASE IF EXISTS my_guitar_shop2; CREATE DATABASE my_guitar_shop2; USE my_guitar_shop2; -- create the tables for the database CREATE TABLE customers customerid INT NOT NULL AUTO_INCREMENT, emailaddress VARCHAR255) NOT NULL, password VARCHAR60) NOT NULL, firstname VARCHAR60) NOT NULL, lastname VARCHAR60) NOT NULL, shipaddressid INT DEFAULT NULL, billingaddressid INT DEFAULT NULL, PRIMARY KEY customerid), UNIQUE INDEX emailaddress emailaddress) 2017, Mike Murach & Associates, Inc. C17, Slide 33 2017, Mike Murach & Associates, Inc. C17, Slide 36 6

The SQL script that creates the database cont.) CREATE TABLE addresses addressid INT NOT NULL AUTO_INCREMENT, line1 VARCHAR60) NOT NULL, line2 VARCHAR60) DEFAULT NULL, city VARCHAR40) NOT NULL, state VARCHAR2) NOT NULL, zipcode VARCHAR10) NOT NULL, phone VARCHAR12) NOT NULL, disabled TINYINT1) NOT NULL DEFAULT 0, PRIMARY KEY addressid), INDEX customerid customerid) The SQL script that creates the database cont.) CREATE TABLE products productid INT NOT NULL AUTO_INCREMENT, categoryid INT NOT NULL, productcode VARCHAR10) NOT NULL, productname VARCHAR255) NOT NULL, description TEXT NOT NULL, listprice DECIMAL10,2) NOT NULL, discountpercent DECIMAL10,2) NOT NULL DEFAULT 0.00, dateadded DATETIME NOT NULL, PRIMARY KEY productid), INDEX categoryid categoryid), UNIQUE INDEX productcode productcode) CREATE TABLE categories categoryid INT NOT NULL AUTO_INCREMENT, categoryname VARCHAR255) NOT NULL, PRIMARY KEY categoryid) 2017, Mike Murach & Associates, Inc. C17, Slide 37 2017, Mike Murach & Associates, Inc. C17, Slide 40 The SQL script that creates the database cont.) CREATE TABLE orders orderid INT NOT NULL AUTO_INCREMENT, orderdate DATETIME NOT NULL, shipamount DECIMAL10,2) NOT NULL, taxamount DECIMAL10,2) NOT NULL, shipdate DATETIME DEFAULT NULL, shipaddressid INT NOT NULL, cardtype INT NOT NULL, cardnumber CHAR16) NOT NULL, cardexpires CHAR7) NOT NULL, billingaddressid INT NOT NULL, PRIMARY KEY orderid), INDEX customerid customerid) The SQL script that creates the database cont.) CREATE TABLE administrators adminid INT NOT NULL AUTO_INCREMENT, emailaddress VARCHAR255) NOT NULL, password VARCHAR255) NOT NULL, firstname VARCHAR255) NOT NULL, lastname VARCHAR255) NOT NULL, PRIMARY KEY adminid) -- Create a user and grant privileges to that user GRANT SELECT, INSERT, UPDATE, DELETE ON * TO mgs_user@localhost IDENTIFIED BY 'pa55word'; 2017, Mike Murach & Associates, Inc. C17, Slide 38 2017, Mike Murach & Associates, Inc. C17, Slide 41 The SQL script that creates the database cont.) CREATE TABLE orderitems itemid INT NOT NULL AUTO_INCREMENT, orderid INT NOT NULL, productid INT NOT NULL, itemprice DECIMAL10,2) NOT NULL, discountamount DECIMAL10,2) NOT NULL, quantity INT NOT NULL, PRIMARY KEY itemid), INDEX orderid orderid), INDEX productid productid) 2017, Mike Murach & Associates, Inc. C17, Slide 39 7