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