Mysql Part 1
Mysql Part 1
Introduction to SQL
SQL stands for Structural Query Language, and SQL is used for storing, manipulation, and
retrieving data from the database.
History of SQL
The SQL(Structural Query language) was first created in the 1970s by IBM researchers Raymond
Boyce and Donald Chamberlin. The Query language, known then as SEQUEL, was created
following the publishing of Edgar Frank Todd's paper, In 1970, A Relational Model of Data for
Large Shared Data Banks.
In his paper, Todd proposed that all the data in a database be represented in the form of relations. It
was based on this theory that Chamberlin and Boyce came up with SQL. The original SQL version
was designed to retrieve and manipulate data stored in IBM's original RDBMS known as "System
R." It wasn't until several years later, however, that the Structural Query language was made
available publicly. In 1979, a company named as Relational Software, which later became Oracle,
commercially released its version of the SQL language called Oracle V2.
Since that time, the American National Standards Institute (ANSI) and the International Standards
Organization have deemed the SQL language as the standard language in relational database
communication. While major SQL vendors do modify the language to their desires, most base their
SQL programs off of the ANSI approved version.
What is Database?
A database is a well-ordered collection of data. A database is an electronic system that permits data
to be easily manipulated, accessed, and updated, or an organization uses a database as a method of
managing, storing, and retrieving information. Modern databases are handled using a database
management system (DBMS).
Relational Database
Relational Databases are used to store data in tables (rows and columns). Some common
relational database management systems that use SQL are Oracle, Sybase,
Microsoft SQL Server, Access, Ingres, etc.
SQL and Relational Databases
A Relational Database contains tables that store the data that is related in some way. SQL is the
query language that allows retrieval and manipulation of table data in the relational database. The
database below has two tables: one with data on Users and another with data on Products.
1. SQL QUERY
A database most often contains tables. Some name identifies each table. The table includes
records(rows) with Data. To access those records, we need SQL Syntax. Most of the action you
need to perform Database by using the SQL Statement.
Note: SQL keywords are not case-sensitive (e.g., select as SELECT)
The syntax of the language describes the language element.
SQL syntax is somewhat like simple English sentences.
Keywords include SELECT, UPDATE, WHERE, ORDER BY ETC.
Four fundamental operations that can apply to any databases are:
1. Read the Data -- SELECT
2. Insert the new Data -- INSERT
3. Update existing Data -- UPDATE
4. Remove Data –DELETE
These operations are referred to as the CRUD (Create, Read, Update, Delete).
The SELECT statement permits you to read data from one or more tables.
The general syntax is:
SELECT first_name, last_name
FROM customer;
Example: Read the first_name and last_name from table customer.
MySQL Syntax:
SELECT first_name, last_name,email
FROM customer WHERE first_name = ‘AUSTIN’
LIMIT 20;
The SQL MIN() AND MAX() FUNCTION
The MIN() function in SQL returns the smallest value of the selected column from the table. The
MAX() function in SQL returns the largest value of the selected column from the table.
MIN() Syntax
SELECT MIN(address_id)
FROM customer;
MAX() Syntax
SELECT MAX(address_id)
FROM customer;
AVG() Syntax
SELECT AVG(active)
FROM customer;
SUM() Syntax
SELECT SUM(active)
FROM customer
The SQL LIKE-OPERATOR
The LIKE operator is used with the WHERE clause to find for a specified pattern in an attribute.
The two wildcards are used in conjunction with the LIKE operator:
% - it represents zero, one, or multiple characters
_ - it represents a single character
Note: MS Access uses an asterisk (*) in place of the percent sign (%)and a question mark (?) in
place of the underscore (_).
The ‘%’ and the ‘_’ can also be used in combinations.
LIKE Syntax
SELECT column1, column2, ...
FROM table_name
WHERE column LIKE pattern;
Selects all columns of the customer with a first_name starting with "D".
SELECT * FROM customer
WHERE first_name LIKE 'D%';
Selects all columns of the customer with a first_name Ending with "E":
SELECT * FROM customer
WHERE first_name LIKE '%E';
Selects all columns of the customer with a first_name that have "or" in any position.
SELECT * FROM customer
WHERE first_name LIKE '%or%';
Selects all columns of the customer with a first_name that starts with "a" and ends with "o":
SELECT * FROM customer
WHERE first_name LIKE 'a%o';
Selects all columns of the customer with a first_name that starts with "a" and are at least six
characters in length:
SELECT * FROM customer
WHERE first_name LIKE 'a__%';
Select all the columns from the customer with customer_id, not between 1 to 570.
SELECT * FROM customer WHERE customer_id NOT BETWEEN 1 AND 570;
The SQL ALIAS
Aliases are used to give a nickname to a column in a table, a temporary name. Aliases are used to
make column names more readable to the user.
Alias Column Syntax
SELECT first_name AS first, last_name AS last
FROM customer;
Creates two aliases, one for the first_name column and one for the last_name column:
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Count the number of active and non-active customers
SELECT COUNT(customer_id) FROM customer GROUP BY active
Note: The column names in the output are usually equal to the column names in the first SELECT
statement in the UNION.
2. SQL JOIN
The SQL Join help in retrieving data from two or more database tables. The tables are mutually
related using primary keys and foreign keys.
Type of Join
INNER JOIN
The INNER JOIN is used to print rows from both tables that satisfy the given condition. For
example, the user wants to get a list of users who have rented movies together with titles of movies
rented by them. Users can use an INNER JOIN for that, which returns rows from both tables that
satisfy with given conditions.
Fig. INNER JOIN
The INNER JOIN keyword selects records that have matching values in both the tables.
INNER JOIN Syntax
SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;
LEFT JOIN
The LEFT JOIN returns all the records from the table1 (left table) and the matched records from
the table2 (right table). The output is NULL from the right side if there is no match.
Left Join
RIGHT JOIN
The RIGHT JOIN is the opposite of LEFT JOIN. The RIGHT JOIN prints all the columns from the
table2(right table) even if there no matching rows have been found in the table1 (left table). If there
no matches have been found in the table (left table), NULL is returned.
RIGHT JOIN
RIGHT JOIN Syntax
SELECT column_name(s)
FROM table1
RIGHT JOIN table2 ON table1.column_name = table2.column_name;
SELECT city.city_id, country.country, city.last_update, country.last_update FROM city
RIGHT JOIN country ON city.country_id = country.country_id
Full Join
Tip: FULL OUTER JOIN and FULL JOIN are the same.
FULL OUTER JOIN Syntax
SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2
ON table1.column_name = table2.column_name WHERE condition;
Note: MySQL does not support the Full Join, so we can perform left join and right join separately
then take the union of them.
SELECT * FROM t1
LEFT JOIN t2 ON t1.id = t2.id
UNION
SELECT * FROM t1
RIGHT JOIN t2 ON t1.id = t2.id
SELF-JOIN
A self-JOIN is a regular join, but the table is joined with itself.
Self -JOIN Syntax
SELECT column_name(s)
FROM table1 T1, table1 T2
WHERE condition;
3. SQL DATABASE
The SQL CREATE DATABASE STATEMENT
The CREATE DATABASE statement in SQL is used to create a new SQL database.
Syntax
CREATE DATABASE database_name;
Let’s create a database and give name as testdb
CREATE database testdb;
Now, let’s check the databases in MySQL by using show databases query.
Show databases;
Now, let’s check the databases in MySQL by using show databases query after dropping the
testdb.
SHOW databases;
The created database(testdb) has been dropped.
The table has dropped after running the query drop table table_name. As we can see, the table does
not exist after dropped.
Now we are going to create the same table again to insert the values in that table.
We have inserted two rows yet. Similarly, we can insert many rows in the table. Finally, we have
added ten rows as we can see in the picture below.
As we can able to see, the last row contains one NULL value.
How to check for NULL Values?
To test for NULL values in the table has to use the IS NULL and IS NOT NULL operators
instead.
IS NULL Syntax
SELECT *
FROM customer WHERE country IS NULL;
UPDATE Syntax
UPDATE customer
SET country = ‘Mexico’ WHERE id = 11;
To change the data type of column values in a table, use the following syntax:
ALTER TABLE customer ADD COLUMN dob date;
We have assigned the dob with the datatype date. But now we want to change the datatype from
date to year.
ALTER TABLE customer MODIFY dob year;
To delete a specific column in a table, use the following syntax (notice that some database systems
don't allow deleting a column):
Syntax:
ALTER TABLE customer
DROP COLUMN email;
The Constraints in SQL can be specified when the table is created with the CREATE TABLE
statement, or after the table is altered with the ALTER TABLE statement.
Syntax:
CREATE TABLE table_name (
column1 datatype constraint,
column2 datatype constraint,
column3 datatype constraint,
....
);
SQL Constraints
SQL constraints are used to specify any rules for the records in a table. Constraints can be used to
limit the type of data that can go into a table. It ensures the accuracy and reliability of the records in
the table, and if there is any violation between the constraint and the record action, the action is
aborted. Constraints can be column level or table level. Column level constraints apply to a column,
and table-level constraints apply to the whole table.
The constraints are commonly used in SQL
CONSTRAINT DESCRIPTION
S
Not Null It Ensures that a column cannot have a NULL value.
Unique It Ensures that all the values in a column are unique.
Primary Key It is a combination of a NOT NULL and UNIQUE. Uniquely identifies each
row in a table.
Foreign Key Uniquely identifies a record /row in another table
Check It checks that all values in a column satisfy a specific condition
Default It gives a default value for a column when no value is specified
Index It is Used to create and retrieve data from the database quickly.
NOT NULL CONSTRAINTS
The NOT NULL constraint enforces a column NOT to accept NULL values. This imposes a field
always to contain a value, which means that the user cannot insert a new record in a table or update
a record without adding a value to this field.
NOTE: By default, a column can hold NULL values.
In the above table, it has specified the id, first_name, and last_name as not null and age as null.
Creates UNIQUE constraint on the "id" column when the "person" table is created
CREATE TABLE person (
id int NOT NULL,
last_name varchar(255) NOT NULL,
first_name varchar(255),
age int,
UNIQUE (ID)
);
We have applied unique constraints on id, and as we can see, it is showing as the primary key.
Create a UNIQUE constraint on the "first_name" column when the "persons" table already
exists.
ALTER TABLE persons
ADD UNIQUE (first_name);
Now we have two unique constraints(id and first_name) in the person table.
To name the UNIQUE constraint, and to define a UNIQUE constraint on multiple columns, use the
following SQL syntax:
ALTER TABLE person
ADD CONSTRAINT UC_person UNIQUE (age, last_name);
Here the age and last_name are converted as unique constraints.
As we can see in the person table The unique constraint(UC_Persons) has been dropped.
To allow the naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY
constraint on multiple columns, use the SQL syntax.
CREATE TABLE person (
id int NOT NULL,
last_name varchar(255) NOT NULL,
first_name varchar(255),
age int,
CONSTRAINT PK_person PRIMARY KEY (id,last_name)
);
Note: In this example, there is only ONE PRIMARY KEY as PK_Person. And the VALUE of the
primary key is made up of two columns (id+ last_name).
Here we have assigned the primary key as “id” on the student table.
Allow the naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint
on multiple columns, use the SQL query:
ALTER TABLE student
ADD CONSTRAINT PK_student PRIMARY KEY (id,first_name);
As we can see from the student table, the primary key has been dropped from the table.
Order Table with Foreign key
CREATE TABLE Orders (OrderID int NOT NULL, OrderNumber int NOT NULL, Id int,
PRIMARY KEY(OrderID), CONSTRAINT FK_customerOrder FOREIGN KEY(Id));
Here the Id is the primary key for the customer table and foreign key for orders table.
Here we have created the Persons table and given a check constraint on the Age column. If the
Age<18, then it will throw an error, as shown below.
INSERT INTO Persons VALUES(1, ‘abc’, ‘aaa’, 17);
For creating a CHECK constraint on multiple columns in the table, use the SQL syntax:
Defining CHECK constraint on multiple columns of a table, use the SQL query:
ALTER TABLE Persons
ADD CONSTRAINT CHK_PersonAge CHECK (Age>=18 AND City='Sandnes');
Here we have dropped the CHK_PersonAge constraints by using the drop statement.
As we can see in the Persons table, the city name is written as Sandnes by Default.
As we can see in the Persons table, the default value of the city has been removed.