MySQL
MySQL
(RDBMS).
MERN --
In this section, we will learn and understand about the ACID properties.
We will learn what these properties stand for and what does each property
is used for. We will also understand the ACID properties with the help of
some examples.
ACID Properties
The expansion of the term ACID defines for:
1) Atomicity
The term atomicity defines that the data remains atomic. It means if any
operation is performed on the data, either it should be performed or
executed completely or should not be executed at all. It further means
that the operation should not break in between or execute partially. In the
case of executing operations on the transaction, the operation should be
completely executed and not partially.
Example: If Remo has account A having $30 in his account from which he
wishes to send $10 to Sheero's account, which is B. In account B, a sum of
$ 100 is already present. When $10 will be transferred to account B, the
sum will become $110. Now, there will be two operations that will take
place. One is the amount of $10 that Remo wants to transfer will be
debited from his account A, and the same amount will get credited to
account B, i.e., into Sheero's account. Now, what happens - the first
operation of debit executes successfully, but the credit operation,
however, fails. Thus, in Remo's account A, the value becomes $20, and to
that of Sheero's account, it remains $100 as it was previously present.
In the above diagram, it can be seenu that after crediting $10, the amount
is still $100 in account B. So, it is not an atomic transaction.
The below image shows that both debit and credit operations are done
successfully. Thus the transaction is atomic.
Thus, when the amount loses atomicity, then in the bank systems, this
becomes a huge issue, and so the atomicity is the main focus in the bank
systems.
2) Consistency
The word consistency means that the value should remain preserved
always. In DBMS, the integrity of the data should be maintained, which
means if a change in the database is made, it should remain preserved
always. In the case of transactions, the integrity of the data is very
essential so that the database remains consistent before and after the
transaction. The data should always be correct.
Example:
3) Isolation
The term 'isolation' means separation. In DBMS, Isolation is the property
of a database where no data should affect the other one and may occur
concurrently. In short, the operation on one database should begin when
the operation on the first database gets complete. It means if two
operations are being performed on two different databases, they may not
affect the value of one another. In the case of transactions, when two or
more transactions occur simultaneously, the consistency should remain
maintained. Any changes that occur in any particular transaction will not
be seen by other transactions until the change is not committed in the
memory.
4) Durability
Durability ensures the permanency of something. In DBMS, the term
durability ensures that the data after the successful execution of the
operation becomes permanent in the database. The durability of the data
should be so perfect that even if the system fails or leads to a crash, the
database still survives. However, if gets lost, it becomes the responsibility
of the recovery manager for ensuring the durability of the database. For
committing the values, the COMMIT command must be used every time
we make changes.
Therefore, the ACID property of DBMS plays a vital role in maintaining the
consistency and availability of data in the database.
Thus, it was a precise introduction of ACID properties in DBMS. We have
discussed these properties in the transaction section also.
An SQL developer must decide what type of data that will be stored inside
each column when creating a table. The data type is a guideline for SQL to
understand what type of data is expected inside of each column, and it also
identifies how SQL will interact with the stored data.
In MySQL there are three main data types: string, numeric, and date and
time.
CHAR(size) A FIXED length string (can contain letters, numbers, and special
BINARY(size) Equal to CHAR(), but stores binary byte strings. The size parameter
VARBINARY(size) Equal to VARCHAR(), but stores binary byte strings. The size parameter
TINYBLOB For BLOBs (Binary Large OBjects). Max length: 255 bytes
BLOB(size) For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data
LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters
LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data
ENUM(val1, val2, val3, ...) A string object that can have only one value, chosen from a list of
If a value is inserted that is not in the list, a blank value will be inserted.
SET(val1, val2, val3, ...) A string object that can have 0 or more values, chosen from a list of
BIT(size) A bit-value type. The number of bits per value is specified in size.
The size parameter can hold a value from 1 to 64. The default value for
size is 1.
TINYINT(size) A very small integer. Signed range is from -128 to 127. Unsigned range is fro
The size parameter specifies the maximum display width (which is 255)
BOOL Zero is considered as false, nonzero values are considered as true.
SMALLINT(size) A small integer. Signed range is from -32768 to 32767. Unsigned range
FLOAT(p) A floating point number. MySQL uses the p value to determine whether
to use FLOAT or DOUBLE for the resulting data type. If p is from 0 to 24,
the data type becomes FLOAT(). If p is from 25 to 53, the data type
becomes DOUBLE()
specified in size. The number of digits after the decimal point is specified
in the d parameter
DOUBLE PRECISION(size, d)
size. The number of digits after the decimal point is specified in the
number for d is 30. The default value for size is 10. The default value
for d is 0.
DEC(size, d) Equal to DECIMAL(size,d)
Note: All the numeric data types may have an extra option: UNSIGNED or
ZEROFILL. If you add the UNSIGNED option, MySQL disallows negative values
for the column. If you add the ZEROFILL option, MySQL automatically also
adds the UNSIGNED attribute to the column.
definition
MySQL Functions
MySQL has many built-in functions.
Function Description
ASCII Returns the ASCII value for the specific character
another string
left)
in a string
in a string
of delimiter occurs
Add several expressions together, and add a "-" separator between them:
concat_ws("-","sql","online tutorial","edubridge") |
+----------------------------------------------------+
| sql-online tutorial-edubridge
+---------------------------+
| 2
Number of Records: 1
FIND_IN_SET("q", "s,p,l")
250,500.56
+------------------------------------------+
| Example.com
Output is 2
select locate('p','pavitra');
+-----------------------+
| locate('p','pavitra') |
+-----------------------+
| 1|
select lpad('edubridge',20,'abc');
+----------------------------+
| lpad('edubridge',20,'abc') |
+----------------------------+
| abcabcabcabedubridge
+-----------+
| ltrimfun |
+-----------+
| edubridge |
Tut
+--------------------------------------+
| position('edu' in 'onlineedubridge') |
+--------------------------------------+
| 7|
HTML Tutorial
ExtractString
Cool
SQL TutorialABCABCAB
RightTrimmedString
SQL Tutorial
SELECT SPACE(10);
SUBSTRING_INDEX("www.w3schools.com", ".", 1)
www
ADDDATE Adds a time/daste interval to a date and then returns the date
ADDTIME Adds a time interval to a time/datetime and then returns the tim
DATE_ADD Adds a time/date interval to a date and then returns the date
DATE_SUB Subtracts a time/date interval from a date and then returns the
LAST_DAY Extracts the last day of the month for a given date
MAKETIME Creates and returns a time based on an hour, minute, and seco
QUARTER Returns the quarter of the year for a given date value
SUBDATE Subtracts a time/date interval from a date and then returns the
SUBTIME Subtracts a time interval from a datetime and then returns the
time/datetime
TO_DAYS Returns the number of days between a date and date "0000-00
YEARWEEK Returns the year and week number for a given date
MySQL Advanced Functions
Function Description
CASE Goes through conditions and return a value when the first cond
CURRENT_USER Returns the user name and host name for the MySQL account t
server used to authenticate the current client
LAST_INSERT_ID Returns the AUTO_INCREMENT id of the last row that has been
updated in a table
NULLIF Compares two expressions and returns NULL if they are equal. O
the first expression is returned
SESSION_USER Returns the current MySQL user name and host name
SYSTEM_USER Returns the current MySQL user name and host name
USER Returns the currleent MySQL user name and host name
SELECT CURRENT_DATE();
SELECT CURRENT_DATE() + 1;
SELECT DATE("2017-06-15");
SELECT DATE("2017-06-15 09:34:21");
SELECT DATE(OrderDate) FROM Orders;
SELECT DATEDIFF("2017-06-25", "2017-06-15");
SELECT DATE_ADD("2017-06-15", INTERVAL 10 DAY);
SELECT DAY("2017-06-15");
SELECT DAY(CURDATE());
SELECT EXTRACT(MONTH FROM "2017-06-15");
(CASE
WHEN City IS NULL THEN Country
ELSE City
END);
Int num=100;
Short s=(int)num;
SELECT ISNULL(NULL);
LIMIT Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;
Constraints in mysql
SELECT MIN(column_name)
FROM table_name
WHERE condition;
SELECT MIN(Price) AS SmallestPrice
FROM Products;
SELECT COUNT(ProductID)
FROM Products;
SELECT AVG(Price)
FROM Products;
SELECT SUM(Quantity)
FROM OrderDetails;
Cross join
Self Join
1000 hr Bangalore
10308 2 1996-09-18
10309 37 1996-09-19
10310 77 1996-09-20
Employee project
1 1
INNER JOIN: Returns records that have matching values in both tables
LEFT JOIN: Returns all records from the left table, and the matched
records from the right table
RIGHT JOIN: Returns all records from the right table, and the matched
records from the left table
CROSS JOIN: Returns all records from both tables
MySQL INNER JOIN Keyword
The INNER JOIN keyword selects records that have matching values in both
tables.
Select
d.deptid,e.empname,e.salary,d.deptname,p.prodname,p.company
From employee e
Inner join product p
On e.prodid = p.prodid
Inner join department d
On e.deptid=d.deptid
Select empname,deptname
From employee e
right join department d
On e.deptid = d.deptid;
Select empname,deptname
From employee e
Cross join department d
SELECT e.employee_id,e.first_name,e.salary,
d.department_name,e.department_id,d.department_id
FROM employees e
Left JOIN
Departments d
ON e.department_id = d.department_id;
10308 2 7 1996-09-18 3
10309 37 3 1996-09-19 1
10310 77 8 1996-09-20 2
Example
SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
Note: The INNER JOIN keyword selects all rows from both tables as long as
there is a match between the columns. If there are records in the "Orders"
table that do not have matches in "Customers", these orders will not be
shown!
Example
SELECT Orders.OrderID, Customers.CustomerName,
Shippers.ShipperName
FROM ((Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID)
INNER JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID);
Demo Database
Below is a selection from the "Customers" table:
10308 2 7 1996-09- 3
18
10309 37 3 1996-09- 1
19
10310 77 8 1996-09- 2
20
Example
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName;
Note: The LEFT JOIN keyword returns all records from the left table
(Customers), even if there are no matches in the right table (Orders).
Demo Database
Below is a selection from the "Orders" table:
10308 2 7 1996-09- 3
18
10309 37 3 1996-09- 1
19
10310 77 8 1996-09- 2
20
Example
SELECT Orders.OrderID, Employees.LastName, Employees.FirstName
FROM Orders
RIGHT JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID
ORDER BY Orders.OrderID
Note: The RIGHT JOIN keyword returns all records from the right table
(Employees), even if there are no matches in the left table (Orders).
SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
CROSS JOIN Orders
WHERE Customers.CustomerID=Orders.CustomerID;
empname managername
deji rajshri
ajay muthu
SELECT A.CustomerName AS CustomerName1,
B.CustomerName AS CustomerName2, A.City
FROM Customers A, Customers B
WHERE A.CustomerID <> B.CustomerID
AND A.City = B.City
ORDER BY A.City;
Every SELECT statement within UNION must have the same number of
columns
The columns must also have similar data types
The columns in every SELECT statement must also be in the same
order
UNION Syntax
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
Note: The column names in the result-set are usually equal to the column
names in the first SELECT statement.
Demo Database
Below is a selection from the "Customers" table:
Example
SELECT City FROM Customers
UNION
SELECT City FROM Suppliers
ORDER BY City;
Note: If some customers or suppliers have the same city, each city will only
be listed once, because UNION selects only distinct values. Use UNION ALL to
also select duplicate values!
Example
SELECT City FROM Customers
UNION ALL
SELECT City FROM Suppliers
ORDER BY City;
SQL UNION With WHERE
The following SQL statement returns the German cities (only distinct values)
from both the "Customers" and the "Suppliers" table:
Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;
Example
SELECT 'Customer' AS Type, ContactName, City, Country
FROM Customers
UNION
SELECT 'Supplier', ContactName, City, Country
FROM Suppliers;
Notice the "AS Type" above - it is an alias. SQL Aliases are used to give a
table or a column a temporary name. An alias only exists for the duration of
the query. So, here we have created a temporary column named "Type", that
list whether the contact person is a "Customer" or a Supplier
GROUP BY Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);
Demo Database
Customer table
Example
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;
The following SQL statement lists the number of customers in each country,
sorted high to low:
Example
SELECT COUNT(CustomerID) as count, Country
FROM Customers
GROUP BY Country
ORDER BY count DESC;
Demo Database
Orders table
10249 81 6 1996-07- 1
05
10250 34 4 1996-07- 2
08
ShipperID ShipperName
1 Speedy Express
2 United Package
3 Federal Shipping
Example
SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS NumberOfOrd
ers FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.ShipperID
GROUP BY ShipperName;
MySQL HAVING
Select count(studentid),deptid
From student
Group by deptid
Having count(studentid)>5
Display the student details the learners whose marks are greater
than average marks of semester 4 learners excluding semester 4
Select *from student where s_marks>(Select avg(s_marks) from
student where s_sem=4) and s_sem !=4;
Write a query to find the employees whose salary is less than the
maximum salary of their own department;
Select first_name,salary, department_id from employees eout
Where salary < (select max(salary) from employees ein
Where eout.department_id = ein.department_id);
ANY means that the condition will be true if the operation is true for any of the
values in the range.
IN >ANY
ANY Syntax
SELECT column_name(s)
FROM table_name
WHERE column_name operator ANY
(SELECT column_name
FROM table_name
WHERE condition);
Note: The operator must be a standard comparison operator (=, <>, !=, >,
>=, <, or <=).
ALL means that the condition will be true only if the operation is true for all
values in the range.
Note: The operator must be a standard comparison operator (=, <>, !=, >,
>=, <, or <=).
SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity = 10);
SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity > 99);
SELECT ProductName
FROM Products
WHERE ProductID = ANY
(SELECT ProductID
FROM OrderDetails
WHERE Quantity > 1000);
Kajal Keshpage
Priyanka Kundan Sawant
The INSERT INTO SELECT statement requires that the data types in source and
target tables matches.
Example
INSERT INTO Customers (CustomerName, ContactName, Address, City,
PostalCode, Country)
SELECT SupplierName, ContactName, Address, City,
PostalCode, Country FROM Suppliers;
The following SQL statement copies only the German suppliers into
"Customers":
Example
INSERT INTO Customers (CustomerName, City, Country)
SELECT SupplierName, City, Country FROM Suppliers
WHERE Country='Germany';
MySQL Comments
Comments are used to explain sections of SQL statements, or to prevent
execution of SQL statements.
Any text between -- and the end of the line will be ignored (will not be
executed).
Example
-- Select all:
SELECT * FROM Customers;
The following example uses a single-line comment to ignore the end of a line:
Example
SELECT * FROM Customers -- WHERE City='Berlin';
The following example uses a single-line comment to ignore a statement:
Example
-- SELECT * FROM Customers;
SELECT * FROM Products;
Multi-line Comments
Multi-line comments start with /* and end with */.
Example
/*Select all the columns
of all the records
in the Customers table:*/
SELECT * FROM Customers;
Example
/*SELECT * FROM Customers;
SELECT * FROM Products;
SELECT * FROM Orders;
SELECT * FROM Categories;*/
SELECT * FROM Suppliers;
Example
SELECT CustomerName, /*City,*/ Country FROM Customers;
Indexes are used to retrieve data from the database more quickly than
otherwise. The users cannot see the indexes, they are just used to speed up
searches/queries.
Note: Updating a table with indexes takes more time than updating a table
without (because the indexes also need an update). So, only create indexes
on columns that will be frequently searched against.
If you want to create an index on a combination of columns, you can list the
column names within the parentheses, separated by commas:
Often this is the primary key field that we would like to be created
automatically every time a new record is inserted.
MySQL AUTO_INCREMENT
Keyword
MySQL uses the AUTO_INCREMENT keyword to perform an auto-increment
feature.
To let the AUTO_INCREMENT sequence start with another value, use the following
SQL statement:
When we insert a new record into the "Persons" table, we do NOT have to
specify a value for the "Personid" column (a unique value will be added
automatically):
The SQL statement above would insert a new record into the "Persons" table.
The "Personid" column would be assigned a unique value automatically. The
"FirstName" column would be set to "Lars" and the "LastName" column would
be set to "Monsen".
Note: The date data type are set for a column when you create a new table
in your database!
Orders Table
1 Geitost 2008-11-11
Now, assume that the "Orders" table looks like this (notice the added time-
component in the "OrderDate" column):
we will get no result! This is because the query is looking only for dates with
no time portion.
Tip: To keep your queries simple and easy to maintain, do not use time-
components in your dates, unless you have to!
A view contains rows and columns, just like a real table. The fields in a view
are fields from one or more real tables in the database.
You can add SQL statements and functions to a view and present the data as
if the data were coming from one single table.
Note: A view always shows up-to-date data! The database engine recreates
the view, every time a user queries it.
Example
CREATE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName
FROM Customers
WHERE Country = 'Brazil';
Create view studentView
As
Select stdname,stdmarks,age
From student
Where age=21
Example
SELECT * FROM [Brazil Customers];
The following SQL creates a view that selects every product in the "Products"
table with a price higher than the average price:
Example
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName, Price
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);
The following SQL adds the "City" column to the "Brazil Customers" view:
Example
CREATE OR REPLACE VIEW [Brazil Customers] AS
SELECT CustomerName, ContactName, City
FROM Customers
WHERE Country = 'Brazil';
Example
DROP VIEW [Brazil Customers];
How do I find the position of a character in MySQL?
The POSITION() function returns the position of the first occurrence of a substring in a
string. If the substring is not found within the original string, this function returns 0. This
function performs a case-insensitive search. Note: The LOCATE() function is equal to the
POSITION() function.
When working with SQL Server, you can use theT-SQL LEFT() and RIGHT() functions to
return any given number of characters from the left or right of a string
POSITION() :
This function in MySQL is used for finding the location of a substring in a string. It will
return the location of the first occurrence of the substring in the string. If the substring is not
present in the string then it will return 0.
How do I find a specific word in a MySQL database?