Você está na página 1de 63

MySQL

introduction
by Antun Peicevic
First edition
Technical editor: Marko Maslac
Copyright 2016 Geek University Press
Disclaimer
This book is designed to provide information about MySQL. Every effort has been made
to make this book as complete and as accurate as possible, but no warranty is implied. The
information is provided on an as is basis. Neither the authors, Geek University Press, nor
its resellers, or distributors will be held liable for any damages caused or alleged to be
caused either directly or indirectly by this book. The opinions expressed in this book
belong to the author and are not necessarily those of Geek University Press.
Trademarks
Geek University is a trademark of Signum Soft, LLC, and may not be used without written
permission.
Feedback Information
At Geek University Press, our goal is to create in-depth technical books of the highest
quality and value. Readers feedback is a natural continuation of this process. If you have
any comments about how we could improve our books and learning resources for you, you
can contact us through email at books@geek-university.com. Please include the book title
in your message. For more information about our books, visit our website at http://geekuniversity.com.

About the author


Antun Peicevic is a systems engineer with more than 10 years of experience in the
internetworking field. His certifications include CCNA Routing and Switching, CompTIA
Network+, CompTIA Security+, and much more. He is the founder and editor of geekuniversity.com, an online education portal that offers courses that cover various aspects of
the IT system administration. Antun can be reached at antun@geek-university.com.

About this book
This book teaches you how to work with MySQL, a popular relational database
management system. The book is written for people without much database experience
and is suitable for beginners.

What will you learn
You will learn how to download and install MySQL on your Windows or Linux system.
You will learn how to access MySQL through the command line or GUI, how to create a
database, how to query a database, sort results, and much more. We will also guide you
through some more advanced MySQL topics, such as MySQL functions, aliases, keys, and
such.
















Table of Contents
Chapter 1 - Introduction
What is MySQL?
Database terms
Install MySQL on Windows
Install MySQL on Ubuntu
Access MySQL
Start the command-line interface
Chapter 2 - SQL command syntax
SQL commands syntax
Create a database
Create a user
Create a table
Data types
Chapter 3 - Important SQL commands
Insert new records
Modify a table
Query a database
Advanced SELECT statements
Remove a row
LIMIT clause
Update the contents of a field
Sort results
Use logical operators
Chapter 4 - Advanced usage
Primary keys
MySQL functions
MySQL string functions
MySQL date functions
MySQL aggregate functions
Aliases
Combine multiple SELECT statements

Chapter 1 - Introduction
In this chapter we will describe what really MySQL is and what it is used for. We will
describe some common database terms and then install MySQL on Window and Linux.

What is MySQL?

MySQL is one of the most popular relational database management systems (RDBMS). It
is open source and available under the terms of the GNU General Public License, which
means that you can download, run, share and even modify MySQL for free. MySQL is a
popular choice of database for web applications, and is a component of the widely used
LAMP open-source web application stack.

A relational database management systems (RDBMS) is a database management system
(DBMS) based on the relational database model. MySQL is a fast and easy-to-use
RDBMS and is used by many web applications such as WordPress, phpBB, Joomla!,
Drupal, etc.

MySQL uses a standard form of the well-known SQL data language. SQL stands for
Structured Query Language and it is a special-purpose programming language designed
for managing data held in a relational database management system. Many other RDBMSs
use SQL as well, such as Oracle and Microsoft SQL Server. SQL syntax is loosely based
on English and looks like this:

SELECT name FROM customers WHERE city = Berlin;


MySQL is available on many operating systems, including Windows, Linux, Solaris, OS
X, and FreeBSD. It can be accessed and administer via the command line or a GUI.

Database terms

You need to know the main terms related to MySQL and databases in general:

Database - a container for a collection of MySQL data.
Table - a subcontainer within a database that stores the actual data.
Column - a name of a field within a row.
Row - a single record within a table.
Primary key - a key that uniquely identifies each record in a database table.
Foreign key - a key in one table that points to a Primary key in another table.
Index - a special lookup table that the database search engine use to speed up data
retrieval.

Install MySQL on Windows


Before installing MySQL on Windows, we need to dowload it. Go to
http://dev.mysql.com/downloads/ and select DOWNLOAD under MySQL Community
Server (GPL):


Choose Windows as the platform and download the installer:


If prompted for the login, log in with your account or create a new one. After the
download finishes, start the installer. Accept the license agreement and click Next:

Choose the setup type and click Next:



Click Execute to install the components:


Next, the wizard will guide you through the product configuration:


Choose your network settings of leave the defaults:


Next, you will be prompted to choose the root password:


Next, choose the name for the MySQL Windows service:


Click Execute to apply the changes:


And thats it! MySQL should be installed.


Install MySQL on Linux

Installing MySQL on Linux is really simple and usually involves just a single command.
We will show you how you can install MySQL on Ubuntu, a popular Linux distribution.

Open the shell and type sudo apt-get install mysql-server:


You will be promted for confirmation. Press Y to continue.

During the installation process you will be prompted to enter and repeat the password for
the root user:


And thats it! You have installed MySQL on your Linux machine.



Access MySQL

There are three main ways in which you can access MySQL:

using the command line - you can access your MySQL server using the mysql
command. You need to provide the username and password.


Once inside the MySQL command-line interface, you can execute various commands to
manipulate your databases and tables:


using MySQL Workbench - this is a GUI tool that enables you to manage your
databases. This application enables you to connect to multiple servers and features a
built-in query tool and command shell:


phpMyAdmin - a tool written in PHP that enables you to a MySQL database server from
a user-friendly environment:


NOTE - all SQL commands are the same, regardless of the interface.


Start the command-line interface

To access the command-line interface from Windows, select Start > Run and type cmd:


This will open the Command Prompt. Browse to the directory in which youve installed
MySQL. The MySQL executable can be found in the bin directory. To start the MySQL
command-line interface, enter mysql -u root -p:


You will be prompted for a password. Enter the password youve selected during the
installation process and press enter. You should be in the MySQL command-line interface:

From the MySQL command-line interface you can manage your MySQL Server
installation and your databases.


Chapter 2 - SQL command syntax


In this chapter we will start working with SQL, a special-purpose programming language
used for managing data held in MySQL. We will show you the SQL syntax and some
basic commands: how to create a database, how to create a table, and how to create a user.

SQL commands syntax



MySQL uses a standard form of the well-known SQL data language. The great thing about
SQL is that the code is very easy to read, as opposed to harder programming languages,
such as C or C++. SQL statements are made up of plain English terms. These terms are
called keywords, and every SQL statement is made up of one or more keywords. The SQL
statement that youll probably use most frequently is the SELECT statement, for example:

SELECT * FROM customers;


All SQL commands and keywords are case-insensitive. However, most people write SQL
commands (such as SELECT, FROM, LIMIT, etc.) in uppercase.

To separate or to end SQL commands, the semicolon is used. This allows you to issue
more than one command at a time by placing a semicolon after each command:

mysql> USE employees; SELECT * FROM employees LIMIT 10;
Database changed
+++++++
| emp_no | birth_date | first_name | last_name | gender | hire_date |
+++++++
| 10001 | 1953-09-02 | Georgi | Facello | M | 1986-06-26 |
| 10002 | 1964-06-02 | Bezalel | Simmel | F | 1985-11-21 |
| 10003 | 1959-12-03 | Parto | Bamford | M | 1986-08-28 |
| 10004 | 1954-05-01 | Chirstian | Koblick | M | 1986-12-01 |
| 10005 | 1955-01-21 | Kyoichi | Maliniak | M | 1989-09-12 |
| 10006 | 1953-04-20 | Anneke | Preusig | F | 1989-06-02 |
| 10007 | 1957-05-23 | Tzvetan | Zielinski | F | 1989-02-10 |
| 10008 | 1958-02-19 | Saniya | Kalloufi | M | 1994-09-15 |
| 10009 | 1952-04-19 | Sumant | Peac | F | 1985-02-18 |
| 10010 | 1963-06-01 | Duangkaew | Piveteau | F | 1989-08-24 |
+++++++
10 rows in set (0.00 sec)


NOTE - table names are case-insensitive on Windows, but case-sensitive on Linux and OS
X. It is recommended to use lowercase characters for tables.


Create a database

To create an MySQL database, the CREATE DATABASE name statement is used. For
example, to create a database named testdb, we can use the following command:

mysql> CREATE DATABASE testdb;
Query OK, 1 row affected (0.01 sec)


We got the message indicating that our query was OK and the time it took to complete the
command. We should see our new database in the output of the SHOW databases
command:

mysql> SHOW databases;
++
| Database |
++
| information_schema |
| employees |
| mysql |
| performance_schema |
| sakila |
| sys |
| testdb |
| world |
++
8 rows in set (0.00 sec)


To work with our new database, we need to issue the USE testdb command:

mysql> USE testdb;
Database changed


Create a user

You should not do all your work in MySQL with the root user; instead, it is recommended
to create users with custom permissions. To create a user, the CREATE USER
user@hostname IDENTIFIED BY password command is used. Here is an
example:

mysql> CREATE USER testuser@localhost IDENTIFIED BY verysecret;
Query OK, 0 rows affected (0.00 sec)


The command above creates a new user called testuser with the password of verysecret
(localhost refers to the local computer MySQL is running on).

When the user is created, it has no permissions to do anything with the databases. The
GRANT command is used to grant privileges. Here is the syntax:

GRANT PRIVILEGES ON database.object TO username@hostname IDENTIFIED BY password


The database.object keywords refer to the database itself and the objects it contains (e.g.
tables). Here are some values of these keywords and their meaning:

*.* - all databases and all their objects.
database.* - the database specified and all its objects.
database.object - the database specified and its specified objects.

For example, to grant the full access to the user testuser@localhost on the testdb
database, the following command can be used:

mysql> GRANT ALL PRIVILEGES ON testdb.* TO testuser@localhost;
Query OK, 0 rows affected (0.00 sec)


NOTE - you can grant only privileges that you already have, and you must have the
privilege to issue the GRANT command.

We can rerun MySQL and log in as testuser to test whether the command above worked:

C:\>mysql -u testuser -p
Enter password: **********

Welcome to the MySQL monitor. Commands end with ; or \g.


Your MySQL connection id is 22
Server version: 5.7.11-log MySQL Community Server (GPL)

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type help; or \h for help. Type \c to clear the current input statement.

mysql> SHOW databases;
++
| Database |
++
| information_schema |
| testdb |
++
2 rows in set (0.00 sec)

mysql>


As you can see from the output above, weve successfully logged in as testuser and
displayed the testdb database.


Create a table

Tables are subcontainers within a database that store the actual data. The database is
created without any tables. To create a table, the following command is used:

CREATE TABLE name(
column_list
) ENGINE name


Here is the explanation of the syntax:


name - specifies the name of the table
column_list - specifies the list and data types of columns, separated by commas.
ENGINE name - specifies the type of database engine to use for this table. If you
dont specify this parameter explicitly, MySQL will use InnoDB by default.

Here is an example. Lets say we want to specify a table called testtable with three colums
- name, surname, and birth year. We can use the following command:

mysql> USE testdb;
Database changed
mysql> CREATE TABLE testtable (name VARCHAR(128), surname VARCHAR(128), year CHAR(4)) ENGINE
MyISAM;
Query OK, 0 rows affected (0.01 sec)

mysql> SHOW tables;
++
| Tables_in_testdb |
++
| testtable |
++
1 row in set (0.00 sec)


To check how our new table looks like, we can use the following command:

mysql> DESCRIBE testtable;
++++++-+
| Field | Type | Null | Key | Default | Extra |
++++++-+
| name | varchar(128) | YES | | NULL | |
| surname | varchar(128) | YES | | NULL | |
| year | char(4) | YES | | NULL | |
++++++-+
3 rows in set (0.03 sec)

Note how each column has a specific data type and the size (e.g.,VARCHAR(255)). This
data type is very useful, as it serves a guideline for MySQL to understand what type of
data is expected inside of each column, and it also identifies how MySQL interacts with
the stored data.. For example, the column year has predictable values, so instead of
VARCHAR we have used the more efficient CHAR(4) data type. This parameter of 4
allows for 4 bytes of data, supporting all years from 999 to 9999.

Data types

A data type defines what kind of value a column in a database table can contain. This
parameter tells MySQL the type of data that will be stored inside each table column, so
MySQL can plan the size of databases and perform lookups and searches more effectively.

In the previous chapter weve defined the VARCHAR and CHAR data types. MySQL
offers many additional data types, including string, numeric, and spatial data types. Here is
a description of the most important ones:

CHAR - a fixed-length string.
VARCHAR - a variable-length string.
BINARY - a fixed-length binary string. Used to store strings of full bytes that do
not have an associated character set (such as GIFs).
BLOB - a Binary Large OBject. Used for binary data in excess of 65,536
bytes in size.
INT - a standard integer numerical.
FLOAT - a single-precision floating point number.
DATE - a date value in YYYY-MM-DD format.
TIME - a time value in HH:MM:SS format.
DATETIME - a date and time value in YYYY-MM-DD HH:MM:SS format.


Chapter 3 - Important SQL commands


In this chapter we will show you some common SQL command used to manage a
database. We will describe how you can insert new records in a table, modify a table,
update the contents of a field We will also show you how to query a database using the
SELECT statement.

Insert new records



To insert new records in an MySQL table, the INSERT INTO command is used. INSERT
INTO allows you to insert one or more rows into a table you specify. Here is the syntax:

INSERT INTO table_name (column1, column2) VALUES (value1, value2,);


The table_name parameter specifies the table you would like to insert a row into. After
the table name, a list of comma-separated column names is specified. This tells MySQL
that these are the fields into which the data will be inserted. Finally, after the VALUES
keyword, a comma-separated values of the corresponding columns are specified.

Here is an example. In the previous chapters weve created an empty table called
testtable. This table contains three columns: name, surname, and year. Lets say that we
want to insert a new record. Here is how we would do that:

mysql> INSERT INTO testtable (name, surname, year) VALUES (Amy,Goodridge,19
91);
Query OK, 1 row affected (0.01 sec)


To display the content of our table, we can use the SELECT * FROM testtable
command:

mysql> SELECT * FROM testtable;
++++
| name | surname | year |
++++
| Amy | Goodridge | 1991 |
++++
1 row in set (0.00 sec)


As you can see from the output above, the record was successfully added to the table.

If you specify the value of the corresponding column for all columns in the table, you
dont need to specify the column names, only their values. Here is an example:

mysql> INSERT INTO testtable VALUES (Mark,Smith,1955);

Query OK, 1 row affected (0.00 sec)



mysql> SELECT * FROM testtable;
++++
| name | surname | year |
++++
| Amy | Goodridge | 1991 |
| Mark | Smith | 1955 |
++++
2 rows in set (0.00 sec)


Notice how we didnt specify the column names in the command displayed above.


Modify a table

The ALTER TABLE statement is used to change the existing table structure. It can be
used to add or remove columns, change the column type, rename a table, etc.

Rename a table

The ALTER TABLE statement can be used to rename a table. The syntax:

ALTER TABLE old_name RENAME TO new_name


Here is how we can rename our table from testtable to testtb:

mysql> ALTER TABLE testtable RENAME TO testtb;
Query OK, 0 rows affected (0.01 sec)


Change the column data type

We can change the data type of a column using the ALTER TABLE statement. Here is
the syntax:

ALTER TABLE table_name MODIFY column_name new_type


For example, to change the data type of a column called year from CHAR to INT, we can
use the following command:

mysql> ALTER TABLE testtb MODIFY year INT;
Query OK, 2 rows affected (0.02 sec)
Records: 2 Duplicates: 0 Warnings: 0


Add a new column

We can use the ALTER TABLE statement to add a new column to our table. Here is the
syntax:

ALTER TABLE table_name ADD COLUMN column_name TYPE


Here is an example. To add a new column called postcode of the INT type to our table
testtb, we can use the following command:

mysql> ALTER TABLE testtb ADD COLUMN postcode INT;
Query OK, 2 rows affected (0.01 sec)
Records: 2 Duplicates: 0 Warnings: 0

mysql> SELECT * FROM testtb;
++++-+
| name | surname | year | postcode |
++++-+
| Amy | Goodridge | 1991 | NULL |
| Mark | Smith | 1955 | NULL |
++++-+
2 rows in set (0.00 sec)


Remove a column

You can use the following ALTER TABLE statement to drop a column from a table:

ALTER TABLE table_name DROP COLUMN column_name


To remove the column postcode weve created in the previous step, we would use the
following command:

mysql> ALTER TABLE testtb DROP COLUMN postcode;
Query OK, 2 rows affected (0.01 sec)
Records: 2 Duplicates: 0 Warnings: 0

mysql> SELECT * FROM testtb;
++++
| name | surname | year |
++++
| Amy | Goodridge | 1991 |
| Mark | Smith | 1955 |
++++
2 rows in set (0.00 sec)



Query a database

Weve learned that a table consists of rows and columns. Often, you want to see a subset
rows, a subset of columns, or a combination of two. To query data from tables in MySQL,
the SELECT statement is used. Here is the basic syntax:

SELECT column_name,column_name FROM table_name


The SELECT statement is used to control which columns and rows will be displayed. For
example, if we only want to display the first name and the surname of all users in our
testtb, we would use the following command:

mysql> SELECT name, surname FROM testtb;
+++
| name | surname |
+++
| Amy | Goodridge |
| Mark | Smith |

+++
2 rows in set (0.00 sec)


To display every column in the table, we can use the asterix (*) character:

mysql> SELECT * FROM testtb;
++++
| name | surname | year |
++++
| Amy | Goodridge | 1991 |
| Mark | Smith | 1955 |
++++
2 rows in set (0.00 sec)



Advanced SELECT statements

We can use many different clauses to change the behaviour of the SELECT statement. In
this chapter we will describe and give examples of some common ones.

Display the number of rows in the table

We can use the COUNT() function to return the number of rows that matches a specified
criteria. For example, to display the number of all rows in a table, we can use the
following command:

mysql> SELECT * FROM testtb;
++-++
| name | surname | year |
++-++
| Amy | Goodridge | 1991 |
| Mark | Smith | 1955 |
| John | von Neumann | 1921 |
| John | Jones | 1985 |
++-++
4 rows in set (0.00 sec)


mysql> SELECT COUNT(*) FROM testtb;
+-+
| COUNT(*) |
+-+
| 4 |
+-+
1 row in set (0.00 sec)


Remove duplicate rows

Sometimes, when querying data from a table, you might get duplicate rows. To remove
these duplicate rows you use the DISTINCT clause in the SELECT statement. For
example, lets say that we want a list of all first name in our table. If we select just the
name column from a table, we will get duplicate results:

mysql> SELECT name FROM testtb;
++
| name |
++
| Amy |
| Mark |
| John |
| John |
++
4 rows in set (0.00 sec)


Notice how the name John appears twice. To weed out multiple entries, we can use the
DISTINCT clause:

mysql> SELECT DISTINCT name FROM testtb;
++
| name |
++
| Amy |
| Mark |
| John |

++
3 rows in set (0.01 sec)


Filter records

You can narrow down queries by returning only those where a certain expression is true.
To do that, the WHERE clause is used. Here is the syntax:

SELECT column_name FROM table_name WHERE column_name operator value


Here is an example. Lets say that we want to select all rows with the value John in the
name column:

mysql> SELECT * FROM testtb;
++-++
| name | surname | year |
++-++
| Amy | Goodridge | 1991 |
| Mark | Smith | 1955 |
| John | von Neumann | 1921 |
| John | Jones | 1985 |
++-++
4 rows in set (0.00 sec)

mysql> SELECT * FROM testtb WHERE name=John;
++-++
| name | surname | year |
++-++
| John | von Neumann | 1921 |
| John | Jones | 1985 |
++-++
2 rows in set (0.01 sec)


NOTE - make sure to use the single quotes around text values when working with strings.

Here is another example. Lets say that we want to select all rows where the year column
is greater than 1980:


mysql> SELECT * FROM testtb WHERE year>1980;
++++
| name | surname | year |
++++
| Amy | Goodridge | 1991 |
| John | Jones | 1985 |
++++
2 rows in set (0.00 sec)



Remove a row

You can use the DELETE command to remove a row from a table. The syntax:

DELETE FROM table_name WHERE column_name operator value


Here is an example. We have our old table testtb:

mysql> SELECT * FROM testtb;
++-++
| name | surname | year |
++-++
| Amy | Goodridge | 1991 |
| Mark | Smith | 1955 |
| John | von Neumann | 1921 |
| John | Jones | 1985 |
++-++
4 rows in set (0.01 sec)


Lets say that we watn to delete the last row. We can do it by specifying the surname
Jones with the WHERE clause:

mysql> DELETE FROM testtb WHERE surname=Jones;
Query OK, 1 row affected (0.00 sec)

mysql> SELECT * FROM testtb;


++-++
| name | surname | year |
++-++
| Amy | Goodridge | 1991 |
| Mark | Smith | 1955 |
| John | von Neumann | 1921 |
++-++
3 rows in set (0.00 sec)


NOTE - make sure to include the WHERE clause. If you omit it, all records in the table
will be deleted!


LIMIT clause

Sometimes tables contain thousands of rows and if you run a SELECT statement to
display all rows, you will impact performance and possibly even crash the system.
However, you can use the LIMIT clause to choose how many rows will be returned in a
query. Here is an example:

mysql> SELECT * FROM employees LIMIT 5;
+++++++
| emp_no | birth_date | first_name | last_name | gender | hire_date |
+++++++
| 10001 | 1953-09-02 | Georgi | Facello | M | 1986-06-26 |
| 10002 | 1964-06-02 | Bezalel | Simmel | F | 1985-11-21 |
| 10003 | 1959-12-03 | Parto | Bamford | M | 1986-08-28 |
| 10004 | 1954-05-01 | Chirstian | Koblick | M | 1986-12-01 |
| 10005 | 1955-01-21 | Kyoichi | Maliniak | M | 1989-09-12 |
+++++++
5 rows in set (0.01 sec)


The employees table mentioned above contains thousands of rows. Using the LIMIT
clause, we were able to display only the first 5 rows.

You can also specify the starting position. For example, to start at the position 2 and return
7 rows, we can use the following command:

mysql> SELECT * FROM employees LIMIT 2,7;
+++++++
| emp_no | birth_date | first_name | last_name | gender | hire_date |
+++++++
| 10003 | 1959-12-03 | Parto | Bamford | M | 1986-08-28 |
| 10004 | 1954-05-01 | Chirstian | Koblick | M | 1986-12-01 |
| 10005 | 1955-01-21 | Kyoichi | Maliniak | M | 1989-09-12 |
| 10006 | 1953-04-20 | Anneke | Preusig | F | 1989-06-02 |
| 10007 | 1957-05-23 | Tzvetan | Zielinski | F | 1989-02-10 |
| 10008 | 1958-02-19 | Saniya | Kalloufi | M | 1994-09-15 |
| 10009 | 1952-04-19 | Sumant | Peac | F | 1985-02-18 |
+++++++
7 rows in set (0.00 sec)


NOTE - notice that the second row in the employees table was not included in the output
above. The LIMIT 2,7 keyword means return seven rows starting from the third row.


Update the contents of a field

One of the most common tasks when working with MySQL databases is the data update.
To update records in an MySQL table, the UPDATE statement is used. Here is the syntax:

UPDATE table_name SET column1=value1,column2=value2, WHERE column_name operator value


As you can see from the syntax above, you first need to specify the table name. Second,
you need to specify which columns will be modified and their new values after the SET
clause. Lastly, you need to specify which rows will be updated using the WHERE clause.

Here is an example. We have our old table testtb:

mysql> SELECT * FROM testtb;
++-++

| name | surname | year |


++-++
| Amy | Goodridge | 1991 |
| Mark | Smith | 1955 |
| John | von Neumann | 1921 |
++-++
3 rows in set (0.00 sec)


Lets say that Amy Goodridge married and changed her surname to Bryant. To update
the surname field, we can use the following syntax:

mysql> UPDATE testtb SET surname=Bryant WHERE surname=Goodridge;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> SELECT * FROM testtb;
++-++
| name | surname | year |
++-++
| Amy | Bryant | 1991 |
| Mark | Smith | 1955 |
| John | von Neumann | 1921 |
++-++
3 rows in set (0.00 sec)


NOTE - make sure to include the WHERE clause; otherwise, the UPDATE statement
will update all rows in the table!


Sort results

You might have noticed that, when you use the SELECT statement to query data, the
results are not sorted in any orders. To sort returned results by one or more columns in
ascending or descending order, you can use the ORDER BY clause. Here is the syntax:

SELECT column1, column2, FROM table_name ORDER BY column1 [ASC|DESC], column2 [ASC|DESC],

Here is a simple example. We will work with the following table:



mysql> SELECT * FROM testtb;
+-+-++
| name | surname | year |
+-+-++
| Amy | Bryant | 1991 |
| Mark | Smith | 1955 |
| John | von Neumann | 1921 |
| Aaron | Rogers | 1995 |
| Brian | Cormier | 1988 |
+-+-++
5 rows in set (0.00 sec)


To sort the results by name, we would use the following command:

mysql> SELECT * FROM testtb ORDER BY name;
+-+-++
| name | surname | year |
+-+-++
| Aaron | Rogers | 1995 |
| Amy | Bryant | 1991 |
| Brian | Cormier | 1988 |
| John | von Neumann | 1921 |
| Mark | Smith | 1955 |
+-+-++
5 rows in set (0.01 sec)


To sort in descending order, we would add the DESC keyword after the column name:

mysql> SELECT * FROM testtb ORDER BY name DESC;
+-+-++
| name | surname | year |
+-+-++
| Mark | Smith | 1955 |
| John | von Neumann | 1921 |
| Brian | Cormier | 1988 |

| Amy | Bryant | 1991 |


| Aaron | Rogers | 1995 |
+-+-++
5 rows in set (0.00 sec)



Use logical operators

You can use the logical operators AND, OR, and NOT to filter records based on more
than one condition and narrow down your selection. Here are the meanings of these
operators:

AND - displays a record if both the first condition and the second condition are true.
OR - displays a record if either the first condition or the second condition is true.
NOT - displays a record if the opposite of the condition is true

Here are the examples. We will work with our old testtb table:

mysql> SELECT * FROM testtb;
+-+-++
| name | surname | year |
+-+-++
| Amy | Bryant | 1991 |
| Mark | Smith | 1955 |
| John | von Neumann | 1921 |
| Aaron | Rogers | 1995 |
| Brian | Cormier | 1988 |
+-+-++
5 rows in set (0.00 sec)


AND example:

mysql> SELECT * FROM testtb WHERE name=Amy AND surname=Bryant;
++++
| name | surname | year |
++++
| Amy | Bryant | 1991 |

++++
1 row in set (0.01 sec)

Chapter 4 - Advanced usage


In this chapter we will show you some advanced MySQL topics. You will learn how to
define primary keys, how to work with MySQL functions, what aliases are and how to
combine multiple SELECT statements.

Primary keys

A primary key is a column or a set of columns that uniquely identifies each record in a
database table. It is usually created when the table is created, but it can also be added to an
existing table that does not have one.

Here are the rules you should be familiar with when creating a primary key for a table:

a primary key must contain unique values.
a primary key column cannot contain NULL values.
each table can have only one primary key.

Here is an example. Lets say that we want to create a table called buyers, with the id
column serving as the primary key. The table should have three other columns: username,
city, and country. Here is the syntax we would use:

CREATE TABLE buyers(
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(40),
city VARCHAR(255),
country VARCHAR(255)
);


The AUTO_INCREMENT attribute causes MySQL to set a unique value for the id
column in every row. Since no value was specified for the AUTO_INCREMENT
column, MySQL will assign sequence numbers automatically.

Lets insert some records into our table:

mysql> INSERT INTO buyers (username, city, country) VALUES (john,London,UK
);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO buyers (username, city, country) VALUES (mark,Berlin,Ger
many);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO buyers (username, city, country) VALUES (alejandra,Madrid


,Spain);
Query OK, 1 row affected (0.00 sec)

mysql> SELECT * FROM buyers;
+-++++
| id | username | city | country |
+-++++
| 1 | john | London | UK |
| 2 | mark | Berlin | Germany |
| 3 | alejandra | Madrid | Spain |
+-++++
3 rows in set (0.00 sec)


Notice how the AUTO_INCREMENT attribute forced the id column to start with 1, and
to increment by 1 for each new record.




MySQL functions

MySQL functions allow you to work on the data right in the database. There are many
MySQL built-in functions for performing calculations on data. They can be divided into
three general types:

String functions - used to manipulate strings of data. Examples of this type of
functions are CONCAT, REPLACE, FORMAT, and LOCATE.
Date functions - used to manipulate temporal values. Examples are DATE,
DATEDIFF, and DATE_ADD.
Aggregate functions - used to perform a calculation on a set of values and return a
single value. Examples are AVG, COUNT, SUM, MIN, and MAX.


MySQL string functions

As weve mentioned in the previous article, the MySQL string functions enable you to
manipulate strings of data. In this article we will describe some common string functions.
We will use our old table testtb for the examples in this chapter:

mysql> SELECT * FROM testtb;
+-+-++
| name | surname | year |
+-+-++
| Amy | Bryant | 1991 |
| Mark | Smith | 1955 |
| John | von Neumann | 1921 |
| Aaron | Rogers | 1995 |
| Brian | Cormier | 1988 |
+-+-++
5 rows in set (0.00 sec)


CONCAT function

The CONCAT function is used to concatenate two or more strings together. For example,
to return the full names of contacts, we will use the CONCAT function to concatenate the
name and surname columns:

mysql> SELECT CONCAT (name, ,surname) FROM testtb;
++
| CONCAT (name, ,surname) |
++
| Amy Bryant |
| Mark Smith |
| John von Neumann |
| Aaron Rogers |
| Brian Cormier |
++
5 rows in set (0.01 sec)


LENGTH function

The LENGTH function returns the length of a string in bytes. To get the actual number of
characters in a string, we can use the CHAR_LENGTH function.

For example, to get the character length of the records in the column name, we would use
the following command:

mysql> SELECT CHAR_LENGTH (name) FROM testtb;
++
| CHAR_LENGTH (name) |
++
| 3 |
| 4 |
| 4 |
| 5 |
| 5 |
++
5 rows in set (0.00 sec)


REPLACE function

To replace a string in a column of a table by a new string, you can use the REPLACE
function. The syntax:

REPLACE(str,old_string,new_string);


As you can see from the syntax above, the REPLACE function accepts three parameters:
it replaces the old_string by the new_string in the str.

Here is an example. To replace a misspelled word webseite in the string About this
webseite, we would use the following command:

mysql> SELECT REPLACE (About this webseite,webseite,website);
++
| REPLACE (About this webseite,webseite,website) |
++
| About this website |
++

1 row in set (0.00 sec)



MySQL date functions

As weve alreadly learned, the MySQL date functions enable you to manipulate temporal
values. In this article we will describe some common date functions.

CURDATE function

The CURDATE function returns the current date in YYYY-MM-DD format. Here is an
example:

mysql> SELECT CURDATE();
++
| CURDATE() |
++
| 2016-03-10 |
++
1 row in set (0.00 sec)




DATEDIFF function

You can use the DATEDIFF function to calculate the number of days between two dates.
Here is an example:

mysql> SELECT DATEDIFF(2016-02-05,1900-03-11) days;
+-+
| days |
+-+
| 42334 |
+-+
1 row in set (0.00 sec)


DATE_ADD function

You can use the DATE_ADD function to add a number of days, weeks, months, or years,
to a date. Here is an example. To add 75 days to a date, we would use the following
command:

mysql> SELECT DATE_ADD(2016-05-07, INTERVAL 75 DAY);
++
| DATE_ADD(2016-05-07, INTERVAL 75 DAY) |
++
| 2016-07-21 |
++
1 row in set (0.00 sec)


Add 2 months:

mysql> SELECT DATE_ADD(2016-05-07, INTERVAL 2 MONTH);
++
| DATE_ADD(2016-05-07, INTERVAL 2 MONTH) |
++
| 2016-07-07 |
++
1 row in set (0.00 sec)


Add 3 years:

mysql> SELECT DATE_ADD(2016-05-07, INTERVAL 3 YEAR);
++
| DATE_ADD(2016-05-07, INTERVAL 3 YEAR) |
++
| 2019-05-07 |
++
1 row in set (0.00 sec)


DAYNAME function


Returns the name of the weekday for the date specified. Here is an example:

mysql> SELECT DAYNAME(2016-03-10);
++
| DAYNAME(2016-03-10) |
++
| Thursday |
++
1 row in set (0.00 sec)

MySQL aggregate functions



As weve already learned, the MySQL aggregate functions enable you to perform a
calculation on a set of values and return a single value. In this article we will describe
some common aggregate functions.We will use our old table testtb for the examples in
this chapter:

mysql> SELECT * FROM testtb;
+-+-++
| name | surname | year |
+-+-++
| Amy | Bryant | 1991 |
| Mark | Smith | 1955 |
| John | von Neumann | 1921 |
| Aaron | Rogers | 1995 |
| Brian | Cormier | 1988 |
+-+-++
5 rows in set (0.00 sec)


AVG function

You can use the MySQL AVG function to calculate the average value of a set of values or
an expression. For example, to calculate the average birth year of all users in the testtb
table, we would use the following command:

mysql> SELECT AVG(year) FROM testtb;
++

| AVG(year) |
++
| 1970.0000 |
++
1 row in set (0.00 sec)


MIN function

You can use the MIN function to find the minimum value in a set of values. For example,
to find the oldest person in our testtb table, we would use the following command:

mysql> SELECT MIN(year) FROM testtb;
++
| MIN(year) |
++
| 1921 |
++
1 row in set (0.00 sec)


MAX function

You can use the MAX function to get the maximum value in a set of values. For example,
to find the youngest person in our testtb table, we would use the following command:

mysql> SELECT MAX(year) FROM testtb;
++
| MAX(year) |
++
| 1995 |
++
1 row in set (0.00 sec)


Aliases

An alias is just an alternate name for a field or value that improves the readability of the
queries. They are assigned with the AS keyword and can be single words or complete
strings.

Consider the following example to understand the usefulness of aliases. Lets say that we
want to return the current date. We can do it with the following command:

mysql> SELECT CURDATE();
++
| CURDATE() |
++
| 2016-03-10 |
++
1 row in set (0.00 sec)


Notice how the column returned was named CURDATE(). We can define more user
friendly name for the column using aliases. Here is how we would do that:

mysql> SELECT CURDATE() AS CurrentDate;
+-+
| CurrentDate |
+-+
| 2016-03-10 |
+-+
1 row in set (0.00 sec)


The column now has a more descriptive name - CurrentDate.


Combine multiple SELECT statements

You can combine multiple SELECT statements into one result set using the UNION
operator. The syntax is:

SELECT column1, column2 UNION SELECT column1, column2

Here is an example. Lets say that we have the following two tables:

mysql> SELECT * FROM buyers;
+-++++
| id | username | city | country |
+-++++
| 1 | john | London | UK |
| 2 | mark | Berlin | Germany |
| 3 | alejandra | Madrid | Spain |
+-++++
3 rows in set (0.00 sec)

mysql> SELECT * FROM testtb;
+-+-++
| name | surname | year |
+-+-++
| Amy | Bryant | 1991 |
| Mark | Smith | 1955 |
| John | von Neumann | 1921 |
| Aaron | Rogers | 1995 |
| Brian | Cormier | 1988 |
+-+-++
5 rows in set (0.00 sec)


We want to combine the username column from the buyers table with the name column
from the testtb table. Here is how we would do that:

mysql> SELECT username FROM buyers UNION SELECT name FROM testtb;
++
| username |
++
| john |
| mark |
| alejandra |
| Amy |
| Aaron |
| Brian |

++
6 rows in set (0.00 sec)


NOTE - the number of columns in the SELECT statements must be equal.

Você também pode gostar