Lecture 5. Monday, September 15, 2014

Similar documents
Unit 1 - Chapter 4,5

CSC Web Programming. Introduction to SQL

How to use SQL to create a database

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

Relational databases and SQL

Lecture 13: MySQL and PHP. Monday, March 26, 2018

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

SQL Data Definition Language: Create and Change the Database Ray Lockwood

October 29, Copyright 2012 by World Class CAD, LLC. All Rights Reserved.

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

Lecture 17. Monday, November 17, 2014

Database Systems. phpmyadmin Tutorial

EE221 Databases Practicals Manual

Mysql interview questions and answers

Relational Database Development

Lecture 8. Monday, September 29, 2014


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

MySQL by Examples for Beginners

Unit 27 Web Server Scripting Extended Diploma in ICT

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

chapter 2 G ETTING I NFORMATION FROM A TABLE

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

SQL BASICS WITH THE SMALLBANKDB STEFANO GRAZIOLI & MIKE MORRIS

Databases (MariaDB/MySQL) CS401, Fall 2015

MySQL and MariaDB. March, Introduction 3

SQL Commands & Mongo DB New Syllabus

STRUCTURED QUERY LANGUAGE (SQL)

WHAT IS A DATABASE? There are at least six commonly known database types: flat, hierarchical, network, relational, dimensional, and object.

STOP DROWNING IN DATA. START MAKING SENSE! An Introduction To SQLite Databases. (Data for this tutorial at

CGS 3066: Spring 2017 SQL Reference

Introduction to Databases. MySQL Syntax Guide: Day 1

Review. Objec,ves. Example Students Table. Database Overview 3/8/17. PostgreSQL DB Elas,csearch. Databases

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

Database Management Systems by Hanh Pham GOALS

Data and Tables. Bok, Jong Soon

G64DBS Database Systems. Lecture 7 SQL SELECT. The Data Dictionary. Data Dictionaries. Different Sections of SQL (DDL) Different Sections of SQL (DCL)

30. Structured Query Language (SQL)

Relational Database Language

Chapter-14 SQL COMMANDS

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

MySQL Workshop. Scott D. Anderson

Chapter 7. Introduction to Structured Query Language (SQL) Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel

SQL DATA MANIPULATION. Prepared By: Dr. Vipul Vekariya.

COMP 430 Intro. to Database Systems. Encapsulating SQL code

Mobile Forms Integrator

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

Introduction to Databases and SQL

Today Learning outcomes LO2

DATABASE MANAGEMENT SYSTEMS

MySQL. Prof.Sushila Aghav

SQL: Concepts. Todd Bacastow IST 210: Organization of Data 2/17/ IST 210

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

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

User's Guide c-treeace SQL Explorer

Server 2 - MySQL #1 Lab

SynApp2 Walk through No. 1

CSCU9Q5 Introduction to MySQL. Data Definition & Manipulation (Over ~two Lectures)

Simple Quesries in SQL & Table Creation and Data Manipulation

More MySQL ELEVEN Walkthrough examples Walkthrough 1: Bulk loading SESSION

1.8 Database and data Data Definition Language (DDL) and Data Manipulation Language (DML)

Database Programming with SQL

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

Networks and Web for Health Informatics (HINF 6220)

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

Data Base Lab. The Microsoft SQL Server Management Studio Part-3- By :Eng.Alaa I.Haniy.

This lecture. Basic Syntax

Lecture 7 Tao Wang 1

COPYRIGHTED MATERIAL. Quickstart to MySQL. Chapter 1. So, you ve obtained a copy of this book. Some of you may be competent with MySQL already

Chapter 16: Databases

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

INDEX. 1 Basic SQL Statements. 2 Restricting and Sorting Data. 3 Single Row Functions. 4 Displaying data from multiple tables

MySQL. A practical introduction to database design

Practical 8. SHANKER SINH VAGHELA BAPU INSTITUTE OF TECHNOLGY Subject: - DBMS Branch: - IT/CE Semester: - 3rd. 1. What does SQL stand for?

Chapter 9: MySQL for Server-Side Data Storage

INTERMEDIATE SQL GOING BEYOND THE SELECT. Created by Brian Duffey

COMP 430 Intro. to Database Systems. SQL from application code

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

Chapter 4.23: Using the Client Access Portal

Getting Information from a Table

Database Systems. Bence Molnár

Database Management Systems,

IN THIS CHAPTER,YOU LEARN THE BASICS of databases, including how they

Database Connectivity using PHP Some Points to Remember:

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

Overview of MySQL Structure and Syntax [2]

A <column constraint> is a constraint that applies to a single column.

Oracle 1Z Oracle Database 11g SQL Fundamentals I. Download Full Version :

Careerarm.com. 1. What is MySQL? MySQL is an open source DBMS which is built, supported and distributed by MySQL AB (now acquired by Oracle)

SQL Interview Questions

Computing for Medicine (C4M) Seminar 3: Databases. Michelle Craig Associate Professor, Teaching Stream

SQL Server. Lecture3 Cascading referential integrity constraint

Using MySQL on the Winthrop Linux Systems

MTAT Introduction to Databases

Interview Questions on DBMS and SQL [Compiled by M V Kamal, Associate Professor, CSE Dept]

Databases II: Microsoft Access

205CDE Developing the Modern Web. Assignment 2 Server Side Scripting. Scenario D: Bookshop

Access Intermediate

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 7 Introduction to Structured Query Language (SQL)

COMP519: Web Programming Autumn 2015

Transcription:

Lecture 5 Monday, September 15, 2014

The MySQL Command So far, we ve learned some parts of the MySQL command: mysql [database] [-u username] p [-- local-infile]! Now let s go further 1

mysqldump mysqldump is another command The command produces the SQL statements needed to recreate the database, including CREATE TABLE statements, INSERT statements, etc. It takes many of the same arguments: mysqldump [database] [-u username] p! Most likely, you would want to redirect the output to a file: mysqldump [database] [-u username] p > dump.sql! 2

mysqldump Other variations include: o Only dump specific tables from a database: mysqldump database [-u username] p [table1 [table2 [table3... [tablen]]]]! o Dump multiple databases: mysqldump --databases db1 [db2 [db3... [dbn]]] [-u username] p! o Dump all databases that you have access to: mysqldump --all-databases [-u username] p You can only specify specific tables to dump when using the first option 3

Feeding a File of Commands into MySQL There are two ways of feeding a file of MySQL commands into a MySQL database from the command line o File redirection o source on MySQL shell The file must contain SQL commands exactly as you would enter them into a shell For example, each command must end in a semicolon 4

Feeding a File of Commands into MySQL You would use file redirection in the following way: mysql [database] [-u username] p < file.sql! NOTE: You must do one of the following, or you will get a database not selected error: o Specify the database name on the command line o Add USE databasename to file.sql before any other operations are performed 5

Feeding a File of Commands into MySQL In a MySQL shell, enter the following command: source file.sql! This is different from when we used the LOAD command to import data o o The LOAD command used a file of raw data for the sole purpose of inserting it into a database SOURCE allows us to just execute a series of commands NOTE: You must do one of the following, or you will get a database not selected error: o o o Specify the database name on the command line when you login to MySQL Run the command USE databasename to select a database Add USE databasename to file.sql before any other operations are performed 6

Running Commands from the UNIX Shell You can specify commands from the command line to run through MySQL: mysql database [-u username] p e "command"! Example: mysql wagnerja e "INSERT INTO students (win, first, last) VALUES (900010001, 'John', 'Smith )"! o Note that the command goes in double quotes o The database name must be included o After completion, you ll be back in your UNIX shell, not a MySQL shell 7

Running Commands from the UNIX Shell You can also run commands that produce output Examples: o Redirect output to a file in a tab-delimited format:! mysql wagnerja e "SELECT * FROM students" > outfile.txt! o Display the results in the terminal as if they were run in the mysql shell in a table-like format: mysql wagnerja e "SELECT * FROM students" o If the results are redirected to a file, or through another command like cat, the results appear in a tab-delimited format 8

More SQL Commands for Table Management TRUNCATE TABLE tablename deletes all records from tablename and resets any auto-incrementing counters DELETE FROM tablename deletes all records from tablename o Does not reset auto-incrementing counters o Once we cover SELECT statements, we will add more to this command using the WHERE clause DROP TABLE tablename removes the table from the database and all of its records 9

More SQL Commands for Table Management DROP TABLE will produce an error if the table does not exist, which makes automating processes difficult Example: o Suppose when doing a lab you create a source file o You are trying to create a table and want to drop it first when you attempt again o If there is a syntax error, the table may not create o The next time you run your source file, it will give an error saying the table does not exist SOLUTION: DROP TABLE tablename IF EXISTS! 10

More SQL Commands for Table Management ALTER TABLE allows you to rename tables, add/remove columns and keys, change default values, and change column definitions You cannot just rename a column, you can change a column definition, which allows you to set a new name, but you must redefine the column s data type, default values, etc. For full syntax, see http://dev.mysql.com/doc/refman/5.5/en/ alter-table.html NOTE: For any assignments in this course that require you to submit the SQL statement for a CREATE TABLE, do not create the table and then add several ALTER TABLE statements after it unless you are specifically asked to do so in the directions 11

ALTER TABLE Rename a table: ALTER TABLE oldtablename RENAME newtablename;! Remove a column: ALTER TABLE tablename DROP COLUMN columname;! 12

ALTER TABLE Add a column at the end of a table ALTER TABLE tablename ADD COLUMN columname coldef;! Add a column at the beginning of a table ALTER TABLE tablename ADD COLUMN columname coldef FIRST;! Add a column anywhere else in the table ALTER TABLE tablename ADD COLUMN columname coldef AFTER existingcolname;! 13

ALTER TABLE Example of adding a column: o Suppose the students table was created with the following: CREATE TABLE students (! win int unsigned not null,! firstname varchar(30) not null,! lastname varchar(30) not null,! emailaddress varchar(50) not null,! PRIMARY KEY(win));! o We want to add the column major between last name and email address ALTER TABLE students ADD COLUMN major varchar(4) not null default 'UN' AFTER lastname;! 14

ALTER TABLE Change the definition of a column: ALTER TABLE tablename MODIFY columname newcoldef;! Change a column definition while renaming it: ALTER TABLE tablename MODIFY oldcolumnname newcolumname newcoldef;! 15

ALTER TABLE Example of changing/modifying a column: o Again, suppose the students table was created with the following: CREATE TABLE students (! win int unsigned not null,! firstname varchar(30) not null,! lastname varchar(30) not null,! emailaddress varchar(50) not null,! PRIMARY KEY(win));! o If we want to rename the lastname field to surname, we could do: ALTER TABLE students CHANGE lastname surname varchar(30) NOT NULL;! o If we want to change the length of the email address field from 50 to 60, we could use one of the following: ALTER TABLE students MODIFY emailaddress varchar(60) NOT NULL;! ALTER TABLE students CHANGE emailaddress emailaddress varchar(60) NOT NULL;! 16

ALTER TABLE Remove a primary key: ALTER TABLE tablename DROP PRIMARY KEY; Add a primary key: ALTER TABLE tablename ADD PRIMARY KEY(columname);! Remove a foreign key: We will discuss this when we get to constraints Add a foreign key: ALTER TABLE tablename ADD FOREIGN KEY (columname) REFERENCES table(col);! 17

ALTER TABLE We can combine multiple ALTER TABLE statements into one Again, suppose the students table was created with the following: CREATE TABLE students (! win int unsigned not null,! firstname varchar(30) not null,! lastname varchar(30) not null,! emailaddress varchar(50) not null);! If we want to add the WIN as the primary key, add the major field, and drop the email address column, we could do: ALTER TABLE students! ADD PRIMARY KEY(win),! ADD COLUMN major varchar(4) not null default 'UN',! DROP COLUMN emailaddress;! 18

SELECT Statements SELECT statements allow you to retrieve (or select) statements from a database We ll start with the most basic, simplest SELECT statement To select all records from a table SELECT * FROM tablename;! 19

SELECT Statements To select only particular fields, we replace the * with a list of field names, separated by commas: SELECT field1 FROM tablename;! SELECT field1, field2 FROM tablename;! 20

ORDER BY To sort the table, we add ORDER BY to our syntax: SELECT * FROM tablename ORDER BY field1, field2;! The fields you are sorting don t ncessarily need to be selected as fields: SELECT field1 FROM tablename ORDER BY field2;! By default, sorting is in ascending order If we add DESC after a field name in the ORDER BY, we can sort in descending order SELECT * FROM tablename ORDER BY field1 DESC, field2;! 21

ORDER BY NOTE: If you store numbers in a field with a text data type (such as VARCHAR), your fields will not sort numerically, but in the order that the characters appear Consider the values in a text field of '2' and '18' Although 2 comes before 18 numerically, the fields would be sorted with 18 before 2 WHY? It compares the first character of each when sorting first, not the numerical value, and 1 comes before 2 22

WHERE Clauses We can limit our results by adding a WHERE clause: SELECT * FROM tablename WHERE field = 'textvalue';! SELECT * FROM tablename WHERE field = number;! We can use AND and OR to put additional limitations on our search:! SELECT * FROM tablename WHERE field1 = 'value1' AND field2 = 'value2';! 23

WHERE Clauses We can use other logical operators for comparison, which work with text or numbers: SELECT * FROM tablename WHERE field >= number;! 24

WHERE Clauses We can do wild card search, with %, for text-based fields, using LIKE: o SELECT * FROM tablename WHERE field LIKE 'R%'; will retrieve all values where field starts with an R o SELECT * FROM tablename WHERE field LIKE '%s%'; will retrieve all values where field contains an s 25

WHERE Clauses with DELETE WHERE clauses can also be specified on delete statements To delete all records where field is set to X : DELETE FROM tablename WHERE field = 'X';! 26