Learn SQL statements in MySQL

Madrid Espana

Photo: Calle Gran Vía, Madrid, Spain

Hi, I already have MySQL installed, if you want to install it you need to download MAMP (already have the packages included).

This is my MySQL (is a RDBMS) Installed:

Then you need to download this script to create the databases

Databases Just import the unzipped file called “create-databases.sql” using the tab import of MySQL.

Note: If you have error importing change all the COLLATE=utf8mb4_0900_ai_ci; to COLLATE=utf8_general_ci; and all the CHARSET=utf8mb4 to CHARSET=utf8

Write the code in uppercase or lowercase?

Well, it doesn’t matter, but is a best practice write the SQL statements in uppercase and use lowercase characters for anything else.

Do not forget to include semicolon ; at the end of you queries.

Before we import the create-databases.sql file our databases are:

To select a database use this code:

USE databaseName;

To retrieve all customers from “sql_store” database / customers table:

We need to use the SELECT statement and in front of this we need to specify the columns of the table that we want to retrieve like:

SELECT nameColumns

Or to retrieve all the columns of that table we can use the SELECT like this:

SELECT *

After that we need to specify the table name from we want that information so then write FROM statement with the table name:

SELECT *
FROM customers;

Result: select all the columns from table customers.

To retrieve all customers from “sql_store” database / customers table and apply some filters the columns:

To apply some filters to the data we use WHERE statement

SELECT *
FROM customers
WHERE customer_id = 1;

Result: In this case we will have only one result (row of the table) that pass that filter.

To sort the data we use ORDER BY statement and then specify the columns that we are going to sort the results.

Let suppose that we want to order this customer result by the first_name (column):

SELECT *
FROM customers
WHERE customer_id = 1
ORDER BY first_name;

Result: This doesn’t have changes, because we have only one row (result).

Comments in SQL

So, let’s remove or comment the filter statement (WHERE) to verify our results in ORDER BY base. In this case we can comment the line using 2 hyphen:

SELECT *
FROM customers
-- WHERE customer_id = 1
ORDER BY first_name;

or just deleting the line. 

Result: 

Without Order

With ORDER BY first_name: is ordering all the column first_name in descendent way

Credits Mosh 

By Cristina Rojas.