0% found this document useful (0 votes)
12 views

dbms notes

This document provides an overview of MySQL, a popular open-source relational database management system, and explains its fundamental concepts including databases, SQL language, and various SQL statements such as CREATE, DROP, and ALTER. It covers essential SQL functions and clauses like SELECT, WHERE, DISTINCT, AND, OR, and IN, along with examples to illustrate their usage. The tutorial aims to equip readers with the knowledge to effectively manage and manipulate data within MySQL databases.

Uploaded by

narelasidhportal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

dbms notes

This document provides an overview of MySQL, a popular open-source relational database management system, and explains its fundamental concepts including databases, SQL language, and various SQL statements such as CREATE, DROP, and ALTER. It covers essential SQL functions and clauses like SELECT, WHERE, DISTINCT, AND, OR, and IN, along with examples to illustrate their usage. The tutorial aims to equip readers with the knowledge to effectively manage and manipulate data within MySQL databases.

Uploaded by

narelasidhportal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

What is MySQL

Summary: What is MySQL? This tutorial will provide you with answers and reasons why MySQL is one of the
world’s most popular open-source databases.

Introduction to databases

You interact with data every day…

When you want to listen to your favorite songs, you open your playlist from your smartphone. In this case, the
playlist is essentially a database.

When you take a photo and upload it to your account on a social network like Facebook, your photo gallery
becomes a database.

When you browse an e-commerce website to buy shoes, clothes, and more, you’re using the shopping cart
database.

Databases are everywhere. So what is a database? By definition, a database is simply a structured collection of
data.

The data within a database are naturally related, for example, a product belongs to a product category and
is associated with multiple tags. Hence, we use the term relational database.

In a relational database, we model data like products, categories, tags, etc., using tables. A table contains columns
and rows, much like a spreadsheet.

Tables can relate to one another table using various types of relationships, like one-to-one and one-to-many.

Because we handle a substantial amount of data, we need a way to efficiently define databases, tables, and
process data. Moreover, we want to transform data into valuable information.

This is where SQL comes into play.

SQL – the language of the relational database

SQL stands for the structured query language.

SQL is the standardized language used to access the database.

ANSI/SQL defines the SQL standard and the current version of SQL is SQL:2023. When we refer to the SQL
standard, we are talking about the current SQL version.

SQL is composed of three parts:

1. Data definition language (DDL) includes statements for defining the database and its objects such as
tables, views, triggers, stored procedures, etc.
2. Data manipulation language (DML) contains statements for updating and querying data.
3. Data control language (DCL) allows you to grant permissions to users to access specific data in the
database.

Now that you understand databases and SQL, it’s time to answer the next question…
What is MySQL
The MySQL CREATE DATABASE Statement
The CREATE DATABASE statement is used to create a new SQL database.

Syntax
CREATE DATABASE databasename;

CREATE DATABASE Example


The following SQL statement creates a database called "testDB":

Example
CREATE DATABASE testDB;

The MySQL DROP DATABASE Statement


The DROP DATABASE statement is used to drop an existing SQL database.

Syntax
DROP DATABASE databasename;

DROP DATABASE Example


The following SQL statement drops the existing database "testDB":

Example DROP DATABASE testDB;

The MySQL CREATE TABLE Statement


The CREATE TABLE statement is used to create a new table in a database.

Syntax
CREATE TABLE table_name (
column1 datatype,
column2 datatype,
column3 datatype,
....
);

The column parameters specify the names of the columns of the table.

The datatype parameter specifies the type of data the column can hold (e.g. varchar, integer,
date, etc.).
MySQL CREATE TABLE Example
The following example creates a table called "Persons" that contains five columns: PersonID,
LastName, FirstName, Address, and City:

Example
CREATE TABLE Persons (
PersonID int,
LastName varchar(255),
FirstName varchar(255),
Address varchar(255),
City varchar(255)
);

The PersonID column is of type int and will hold an integer.

The MySQL DROP TABLE Statement


The DROP TABLE statement is used to drop an existing table in a database.

Syntax
DROP TABLE table_name;

MySQL DROP TABLE Example


The following SQL statement drops the existing table "Shippers":

Example
DROP TABLE Shippers;

MySQL ALTER TABLE Statement


The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.

The ALTER TABLE statement is also used to add and drop various constraints on an existing table.

ALTER TABLE - ADD Column


To add a column in a table, use the following syntax:

ALTER TABLE table_name


ADD column_name datatype;

The following SQL adds an "Email" column to the "Customers" table:


Example
ALTER TABLE Customers
ADD Email varchar(255);

ALTER TABLE - DROP COLUMN


To delete a column in a table, use the following syntax (notice that some database systems don't
allow deleting a column):

ALTER TABLE table_name


DROP COLUMN column_name;

The following SQL deletes the "Email" column from the "Customers" table:

Example
ALTER TABLE Customers
DROP COLUMN Email;

ALTER TABLE - MODIFY COLUMN


To change the data type of a column in a table, use the following syntax:

ALTER TABLE table_name


MODIFY COLUMN column_name datatype;

MySQL Constraints
SQL constraints are used to specify rules for the data in a table.

Constraints are used to limit the type of data that can go into a table. This ensures the accuracy
and reliability of the data in the table. If there is any violation between the constraint and the data
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 following constraints are commonly used in SQL:

 NOT NULL - Ensures that a column cannot have a NULL value


 UNIQUE - Ensures that all values in a column are different
 PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table
 FOREIGN KEY - Prevents actions that would destroy links between tables
 CHECK - Ensures that the values in a column satisfies a specific condition
 DEFAULT - Sets a default value for a column if no value is specified
 CREATE INDEX - Used to create and retrieve data from the database very quickly

 PRIMARY KEY on CREATE TABLE


 The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is
created:
 CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);
 To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on
multiple columns, use the following SQL syntax:
 CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
);

MySQL FOREIGN KEY Constraint


The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.

A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another
table.

The table with the foreign key is called the child table, and the table with the primary key is called
the referenced or parent table.

Look at the following two tables:

Persons Table

Orders Table PersonID LastName FirstName Age OrderID OrderNumber PersonID

1 Hansen Ola 30 1 77895 3

2 Svendson Tove 23 2 44678 3

3 Pe ersen Kari 20 3 22456 2

Notice that the "PersonID" column in the "Orders" table points to the "PersonID" column in the
"Persons" table.

The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons" table.

The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders" table.

The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign key column,
because it has to be one of the values contained in the parent table.

FOREIGN KEY on CREATE TABLE


The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders" table is
created:

CREATE TABLE Orders (


OrderID int NOT NULL,
OrderNumber int NOT NULL,
PersonID int,
PRIMARY KEY (OrderID),
FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
);

MySQL CHECK Constraint


The CHECK constraint is used to limit the value range that can be placed in a column.

If you define a CHECK constraint on a column it will allow only certain values for this column.

If you define a CHECK constraint on a table it can limit the values in certain columns based on values
in other columns in the row.

CHECK on CREATE TABLE


The following SQL creates a CHECK constraint on the "Age" column when the "Persons" table is
created. The CHECK constraint ensures that the age of a person must be 18, or older:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
CHECK (Age>=18)
);

MySQL DEFAULT Constraint


The DEFAULT constraint is used to set a default value for a column.

The default value will be added to all new records, if no other value is specified.

DEFAULT on CREATE TABLE


The following SQL sets a DEFAULT value for the "City" column when the "Persons" table is created:

CREATE TABLE Persons (


ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
City varchar(255) DEFAULT 'Sandnes'
);

The MySQL INSERT INTO Statement


The INSERT INTO statement is used to insert new records in a table.

INSERT INTO Syntax

It is possible to write the INSERT INTO statement in two ways:

1. Specify both the column names and the values to be inserted:

INSERT INTO table_name (column1, column2, column3, ...)


VALUES (value1, value2, value3, ...);

2. If you are adding values for all the columns of the table, you do not need to specify the column
names in the SQL query. However, make sure the order of the values is in the same order as the
columns in the table. Here, the INSERT INTO syntax would be as follows:

INSERT INTO table_name


VALUES (value1, value2, value3, ...);

INSERT INTO Example


The following SQL statement inserts a new record in the "Customers" table:

Example
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');

The MySQL UPDATE Statement


The UPDATE statement is used to modify the existing records in a table.

UPDATE Syntax
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

UPDATE Table
The following SQL statement updates the first customer (CustomerID = 1) with a new contact
person and a new city.

Example
UPDATE Customers
SET ContactName = 'Alfred Schmidt', City = 'Frankfurt'
WHERE CustomerID = 1;

MySQL DELETE Statement


The DELETE statement is used to delete existing records in a table.

DELETE Syntax
DELETE FROM table_name WHERE condition;
SQL DELETE Example
The following SQL statement deletes the customer "Alfreds Futterkiste" from the "Customers"
table:

Example
DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';

MySQL COUNT(), AVG() and SUM() Functions


The COUNT() function returns the number of rows that matches a specified criterion.

COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;

The AVG() function returns the average value of a numeric column.

AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;

The SUM() function returns the total sum of a numeric column.

SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;

MySQL SELECT FROM


Summary: in this tutorial, you will learn how to use the basic form of the MySQL SELECT
FROM statement to query data from a table.

Introduction to MySQL SELECT FROM statement


The SELECT statement allows you to select data from one or more tables. To write
a SELECT statement in MySQL, you use this syntax:
SELECT select_list
FROM table_name;Code language: SQL (Structured Query Language) (sql)

In this syntax:

 First, specify one or more columns from which you want to select data after
the SELECT keyword. If the select_list has multiple columns, you need to separate them
by a comma (,).
 Second, specify the name of the table from which you want to select data after
the FROM keyword.

The semicolon (;) is optional, which denotes the end of a statement. If you have two or more
statements, you need to use the semicolon(;) to separate them so that MySQL will execute
each statement individually.

The SELECT and FROM are the keywords. By convention, you write the SQL keywords in
uppercase. However, it’s not mandatory. Because SQL is case-insensitive, you can write the
SQL statement in lowercase, uppercase, etc. For example:
select select_list
from table_name;Code language: SQL (Structured Query Language) (sql)

When executing the SELECT statement, MySQL evaluates the FROM clause before
the SELECT clause:

MySQL SELECT FROM statement examples


We’ll use the employees table in the sample database for the following examples:

MySQL WHERE
Summary: in this tutorial, you will learn how to use the MySQL WHERE clause in
the SELECT statement to filter rows from the result set.

Introduction to MySQL WHERE clause


The WHERE clause allows you to specify a search condition for the rows returned by a query.
The following shows the syntax of the WHERE clause:
SELECT
select_list
FROM
table_name
WHERE
search_condition;Code language: SQL (Structured Query Language) (sql)

The search_condition is a combination of one or more expressions using the logical


operator AND, OR and NOT.

In MySQL, a predicate is a Boolean expression that evaluates to TRUE, FALSE, or UNKNOWN.

The SELECT statement will include any row that satisfies the search_condition in the result set.

Besides the SELECT statement, you can use the WHERE clause in
the UPDATE or DELETE statement to specify which rows to update or delete.

When executing a SELECT statement with a WHERE clause, MySQL evaluates the WHERE clause
after the FROM clause and before the SELECT and ORDER BY clauses:
MySQL WHERE clause examples
We’ll use the employees table from the sample database for the demonstration:

Introduction to MySQL DISTINCT clause


When querying data from a table, you may get duplicate rows. To remove these duplicate
rows, you use the DISTINCT clause in the SELECT statement.

Here’s the syntax of the DISTINCT clause:


SELECT DISTINCT
select_list
FROM
table_name
WHERE
search_condition
ORDER BY
sort_expression;Code language: SQL (Structured Query Language) (sql)

In this syntax, you specify one or more columns that you want to select distinct values after
the SELECT DISTINCT keywords.

If you specify one column, the DISTINCT clause will evaluate the uniqueness of rows based on
the values of that column.

However, if you specify two or more columns, the DISTINCT clause will use the values of these
columns to evaluate the uniqueness of the rows.

When executing the SELECT statement with the DISTINCT clause, MySQL evaluates
the DISTINCT clause after the FROM, WHERE, and SELECT clause and before the ORDER BY clause.

Example:

SELECT
DISTINCT lastname
FROM
employees
ORDER BY

lastname;

Introduction to MySQL AND operator


MySQL doesn’t have a built-in Boolean type. Instead, it uses the number zero as
FALSE and non-zero values as TRUE.

The AND operator is a logical operator that combines two or


more Boolean expressions and returns 1, 0, or NULL:
A AND B

In this expression, A and B are called operands. They can be literal values or
expressions.

The logical AND operator returns 1 if both A and B are non-zero and not NULL. It
returns 0 if either operand is zero; otherwise, it returns NULL.

The logical AND operator returns 1 if both A and B are non-zero and NOT NULL. For
example:

SELECT 1 AND 1;

Introduction to the MySQL OR operator


The MySQL OR operator is a logical operator that combines two Boolean expressions.

A OR BCode language: SQL (Structured Query Language) (sql)

If both A and B are not NULL, the OR operator returns 1 (true) if either A or B is non-
zero. For example:

SELECT 1 OR 1, 1 OR 0, 0 OR 1;Code language: SQL (Structured Query Language) (sql)


+--------+--------+--------+
| 1 OR 1 | 1 OR 0 | 0 OR 1 |
+--------+--------+--------+
| 1| 1| 1|
+--------+--------+--------+
1 row in set (0.00 sec)Code language: plaintext (plaintext)

If both A and B are zero (false), the OR operator returns zero. For example:

SELECT 0 OR 0;

Introduction to the MySQL IN operator


The IN operator allows you to determine if a value matches any value in a list of
values. Here’s the syntax of the IN operator:

value IN (value1, value2, value3,...)Code language: SQL (Structured Query Language)


(sql)

The IN operator returns 1 (true) if the value equals any value in the list
(value1, value2, value3,…). Otherwise, it returns 0.

In this syntax:

 First, specify the value to test on the left side of the IN operator. The value can
be a column or an expression.
 Second, specify a comma-separated list of values to match in the parentheses.
The IN operator is functionally equivalent to a combination of multiple OR operators:

value = value1 OR value = value2 OR value = value3 OR ...Code language: SQL (Structured
Query Language) (sql)

Example:

SELECT
officeCode,
city,
phone,
country
FROM
offices
WHERE
country IN ('USA' , 'France');

Introduction to MySQL BETWEEN Operator


The BETWEEN operator is a logical operator that specifies whether a value is in a
range or not. Here’s the syntax of the BETWEEN operator:

value BETWEEN low AND high;Code language: SQL (Structured Query Language) (sql)

The BETWEEN operator returns 1 if:

value >= low AND value <= highCode language: SQL (Structured Query Language) (sql)

Otherwise, it returns 0.

If the value, low, or high is NULL, the BETWEEN operator returns NULL .

For example, the following statement returns 1 because 15 is between 10 and 20:

SELECT 15 BETWEEN 10 AND 20;Code language: SQL (Structured Query Language)


(sql)

The following example returns 0 because 15 is not between 20 and 30:

SELECT 15 BETWEEN 20 AND 30;

Introduction to MySQL LIKE operator


The LIKE operator is a logical operator that tests whether a string contains a specified
pattern or not.

Here’s the syntax of the LIKE operator:

expression LIKE pattern ESCAPE escape_characterCode language: SQL (Structured Query


Language) (sql)
In this syntax, if the expression matches the pattern, the LIKE operator returns 1.
Otherwise, it returns 0.

MySQL provides two wildcard characters for constructing patterns: Percentage % and
underscore _ .

 The percentage ( % ) wildcard matches any string of zero or more characters.


 The underscore ( _ ) wildcard matches any single character.

For example, s% matches any string starting with the character s such as sun and six.
The se_ matches any string starting with se and is followed by any character such
as see and sea.

When the pattern contains the wildcard character and you want to treat it as a
regular character, you can use the ESCAPE clause.

Typically, you’ll use the LIKE operator in the WHERE clause of the SELECT , DELETE,
and UPDATE statement.

MySQL LIKE operator examples


Let’s practice with some examples of using the LIKE operator. We will use the
following employees table from the sample database for the demonstration:

1) Using MySQL LIKE operator with the percentage (%) wildcard examples

This example uses the LIKE operator to find employees whose first names start with
the letter a:

SELECT
employeeNumber,
lastName,
firstName
FROM
employees
WHERE
firstName LIKE 'a%';

You might also like