dbms notes
dbms notes
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
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.
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.
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;
Example
CREATE DATABASE testDB;
Syntax
DROP DATABASE databasename;
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)
);
Syntax
DROP TABLE table_name;
Example
DROP TABLE Shippers;
The ALTER TABLE statement is also used to add and drop various constraints on an existing table.
The following SQL deletes the "Email" column from the "Customers" table:
Example
ALTER TABLE Customers
DROP COLUMN Email;
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.
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.
Persons Table
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.
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.
The default value will be added to all new records, if no other value is specified.
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:
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');
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;
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';
COUNT() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
AVG() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
SUM() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
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 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.
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:
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;
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;
If both A and B are not NULL, the OR operator returns 1 (true) if either A or B is non-
zero. For example:
If both A and B are zero (false), the OR operator returns zero. For example:
SELECT 0 OR 0;
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');
value BETWEEN low AND high;Code language: SQL (Structured Query Language) (sql)
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:
MySQL provides two wildcard characters for constructing patterns: Percentage % and
underscore _ .
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.
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%';