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

MySQL

The document provides an overview of MySQL as a relational database management system, highlighting its open-source nature and suitability for various application sizes. It explains the ACID properties (Atomicity, Consistency, Isolation, Durability) essential for maintaining data integrity in database transactions. Additionally, it details MySQL data types, including string, numeric, and date/time types, along with various built-in functions for string manipulation.

Uploaded by

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

MySQL

The document provides an overview of MySQL as a relational database management system, highlighting its open-source nature and suitability for various application sizes. It explains the ACID properties (Atomicity, Consistency, Isolation, Durability) essential for maintaining data integrity in database transactions. Additionally, it details MySQL data types, including string, numeric, and date/time types, along with various built-in functions for string manipulation.

Uploaded by

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

MySQL is a widely used relational database management system

(RDBMS).

Oracle ---Java secured not open source

Microsoft sql server ----.net platform ---secured, not open source

MySQL is free and open-source.

MySQL is ideal for both small and large applications.

MERN --

Records or objects ---Mongodb –key and value pair

ACID Properties in DBMS


DBMS is the management of data that should remain integrated when any
changes are done in it. It is because if the integrity of the data is affected,
whole data will get disturbed and corrupted. Therefore, to maintain the
integrity of the data, there are four properties described in the database
management system, which are known as the ACID properties. The ACID
properties are meant for the transaction that goes through a different
group of tasks, and there we come to see the role of the ACID properties.

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:

In the above figure, there are three accounts, A, B, and C, where A is


making a transaction T one by one to both B & C. There are two
operations that take place, i.e., Debit and Credit. Account A firstly debits
$50 to account B, and the amount in account A is read $300 by B before
the transaction. After the successful transaction T, the available amount in
B becomes $150. Now, A debits $20 to account C, and that time, the value
read by C is $250 (that is correct as a debit of $50 has been successfully
done to B). The debit and credit operation from account A to C has been
done successfully. We can see that the transaction is done successfully,
and the value is also read correctly. Thus, the data is consistent. In case
the value read by B and C is $300, which means that data is inconsistent
because when the debit operation executes, it will not be consistent.

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.

Example: If two operations are concurrently running on two different


accounts, then the value of both accounts should not get affected. The
value should remain persistent. As you can see in the below diagram,
account A is making T1 and T2 transactions to account B and C, but both
are executing independently without affecting each other. It is known as
Isolation.

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.

MySQL Data Types


The data type of a column defines what value the column can hold:
integer, character, money, date and time, binary, and so on.

MySQL Data Types (Version 8.0)


Each column in a database table is required to have a name and a data type.

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.

String Data Types

Data type Description

CHAR(size) A FIXED length string (can contain letters, numbers, and special

characters). The size parameter specifies the column length in characters

- can be from 0 to 255. Default is 1

Char(100) ---Premal --6 –94


VARCHAR(size) A VARIABLE length string (can contain letters, numbers, and special

Varchar(100) --premal ----6

characters). The size parameter specifies the maximum column length in

characters - can be from 0 to 65535

BINARY(size) Equal to CHAR(), but stores binary byte strings. The size parameter

specifies the column length in bytes. Default is 1

VARBINARY(size) Equal to VARCHAR(), but stores binary byte strings. The size parameter

specifies the maximum column length in bytes.

TINYBLOB For BLOBs (Binary Large OBjects). Max length: 255 bytes

TINYTEXT Holds a string with a maximum length of 255 characters

TEXT(size) Holds a string with a maximum length of 65,535 bytes

BLOB(size) For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data

MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters

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

possible values. You can list up to 65535 values in an ENUM list.

If a value is inserted that is not in the list, a blank value will be inserted.

The values are sorted in the order you enter them

SET(val1, val2, val3, ...) A string object that can have 0 or more values, chosen from a list of

possible values. You can list up to 64 values in a SET list

Numeric Data Types

Data type Description

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.

BOOLEAN Equal to BOOL

SMALLINT(size) A small integer. Signed range is from -32768 to 32767. Unsigned range

is from 0 to 65535. The size parameter specifies the maximum display

width (which is 255)

MEDIUMINT(size) A medium integer. Signed range is from -8388608 to 8388607. Unsigned

range is from 0 to 16777215. The size parameter specifies the maximum

display width (which is 255)

INT(size) A medium integer. Signed range is from -2147483648 to 2147483647.

Unsigned range is from 0 to 4294967295. The size parameter specifies

the maximum display width (which is 255)

SmallInt Equal to INT(size)

BIGINT(size) A large integer. Signed range is from -9223372036854775808 to

9223372036854775807. Unsigned range is from 0 to

18446744073709551615. The size parameter specifies the maximum

display width (which is 255)


FLOAT(size, d) A floating point number. The total number of digits is specified in size.

The number of digits after the decimal point is specified in the d

parameter. This syntax is deprecated in MySQL 8.0.17, and it will be

removed in future MySQL versions

float(4,2) // 12.89 12346.90

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()

DOUBLE(size, d) A normal-size floating point number. The total number of digits is

specified in size. The number of digits after the decimal point is specified

in the d parameter

DOUBLE PRECISION(size, d)

DECIMAL(size, d) An exact fixed-point number. The total number of digits is specified in

size. The number of digits after the decimal point is specified in the

d parameter. The maximum number for size is 65. The maximum

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.

Date and Time Data Types

Data type Description

DATE A date. Format: YYYY-MM-DD. The supported range is

from '1000-01-01' to '9999-12-31'

DATETIME(fsp) A date and time combination. Format: YYYY-MM-DD

hh:mm:ss. The supported range is from

'1000-01-01 00:00:00' to '9999-12-31 23:59:59'.

Adding DEFAULT and ON UPDATE in the column

definition to get automatic initialization and updating

to the current date and time

TIMESTAMP(fsp) A timestamp. TIMESTAMP values are stored as the

number of seconds since the Unix epoch

('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD

hh:mm:ss. The supported range is from '1970-01-01 00:

00:01' UTC to '2038-01-09 03:14:07' UTC. Automatic


initialization and updating to the current date and time

can be specified using DEFAULT CURRENT_TIMESTAMP

and ON UPDATE CURRENT_TIMESTAMP in the column

definition

TIME(fsp) A time. Format: hh:mm:ss. The supported range is from '-8


'838:59:59'

YEAR A year in four-digit format. Values allowed in four-digit

format: 1901 to 2155, and 0000.


MySQL 8.0 does not support year in two-digit format.

MySQL Functions
MySQL has many built-in functions.

This reference contains string, numeric, date, and some advanced


functions in MySQL.

MySQL String Functions---


predefined
User – defined ---create function

Function Description
ASCII Returns the ASCII value for the specific character

CHAR_LENGTH Returns the length of a string (in characters)

CHARACTER_LENGTH Returns the length of a string (in characters)

CONCAT Adds two or more expressions together

CONCAT_WS Adds two oer more expressions together with a separator

FIELD Returns the index position of a value in a list of values

FIND_IN_SET Returns the position of a string within a list of strings

FORMAT Formats a number to a format like "#,###,###.##",

rounded to a specified number of decimal places

INSERT Inserts a string within a string at the specified position

and for a certain number of characters

INSTR Returns the position of the first occurrence of a string in

another string

LCASE Converts a string to lower-case


LEFT Extracts a number of characters from a string (starting from

left)

LENGTH Returns the length of a string (in bytes)

LOCATE Returns the position of the first occurrence of a substring

in a string

LOWER Converts a string to lower-case

LPAD Left-pads a string with another string, to a certain length

LTRIM Removes leobading spaces from a string

MID Extracts a substring from a string (starting at any position)

POSITION Returns the position of the first occurrence of a substring

in a string

REPEAT Repeats a string as many times as specified

REPLACE Replaces all occurrences of a substring within a string,


with a new substring

REVERSE Reverses a string and returns the result

RIGHT Extracts a number of characters from a string (starting from rig

RPAD Right-pads a string with another string, to a certain length

RTRIM Removes trailing spaces from a string

SPACE Returns a string of the specified number of space characters

STRCMP Compares two strings

SUBSTR Extracts a substring from a string (starting at any position)

SUBSTRING Extracts a substring from a string (starting at any position)

SUBSTRING_INDEX Returns a substring of a string before a specified number

of delimiter occurs

TRIM Removes leading and trailing spaces from a string


UCASE Converts a string to upper-case

UPPER Converts a string to upper-case

Add several expressions together, and add a "-" separator between them:

SELECT CONCAT_WS("-“ "SQL", "Tutorial", "is", "fun!") AS Concaten


atedString;

select concat_ws("-","sql","online tutorial","edubridge");

concat_ws("-","sql","online tutorial","edubridge") |

+----------------------------------------------------+

| sql-online tutorial-edubridge

SELECT FIELD("q", "s", "q", "l");

FIELD("q", "s", "q", "l") |

+---------------------------+

| 2

SELECT FIND_IN_SET("q", "s,q,l");

Number of Records: 1

FIND_IN_SET("q", "s,p,l")

Format the number as "#,###,###.##" (and round with two decimal


places):

SELECT FORMAT(250500.5634, 2);


FORMAT(250500.5634, 2)

250,500.56

SELECT INSERT("edubridge.com", 1, 9, "Example");


INSERT("edubridge.com", 1, 9, "Example") |

+------------------------------------------+

| Example.com

SELECT INSTR("edubridgeindia.com", "d") AS MatchPosition;

Output is 2

select locate('p','pavitra');

+-----------------------+

| locate('p','pavitra') |

+-----------------------+

| 1|

select lpad('edubridge',20,'abc');

+----------------------------+

| lpad('edubridge',20,'abc') |

+----------------------------+

| abcabcabcabedubridge

select ltrim(' edubridge') as ltrimfun;

+-----------+

| ltrimfun |

+-----------+

| edubridge |

Extract a substring from a string (start at position 5, extract 3 characters):

SELECT MID("SQL Tutorial", 5, 3) AS ExtractString;


ExtractString

Tut

select position('edu' in 'onlineedubridge');

+--------------------------------------+

| position('edu' in 'onlineedubridge') |

+--------------------------------------+

| 7|

SELECT REPEAT("SQL Tutorial", 3);

SQL TutorialSQL TutorialSQL Tutorial

SELECT REPLACE("SQL Tutorial", "SQL", "HTML");

HTML Tutorial

SELECT REVERSE("SQL Tutorial");

SELECT RIGHT("SQL Tutorial is cool", 4) AS ExtractString;

ExtractString

Cool

SELECT RPAD("SQL Tutorial", 20, "ABC");

RPAD("SQL Tutorial", 20, "ABC")

SQL TutorialABCABCAB

SELECT RTRIM("SQL Tutorial ") AS RightTrimmedString;

RightTrimmedString

SQL Tutorial

SELECT SPACE(10);

Prints the 10 space.


SELECT STRCMP("SQL Tutorial", "SQL Tutorial");

SELECT SUBSTR("SQL Tutorial", 5, 3) AS ExtractString;

SELECT SUBSTRING("SQL Tutorial", 5, 3) AS ExtractString;

SELECT SUBSTRING_INDEX("www.w3schools.com", ".", 1);

SUBSTRING_INDEX("www.w3schools.com", ".", 1)

www

MySQL Numeric Functions


Function Description

ABS Returns the absolute value of a number

ACOS Returns the arc cosine of a number

ASIN Returns the arc sine of a number

ATAN Returns the arc tangent of one or two numbers

ATAN2 Returns the arc tangent of two numbers

AVG Returns the average value of an expression

CEIL Returns the smallest integer value that is >= to a number


CEILING Returns the smallest integer value that is >= to a number

COS Returns the cosine of a number

COT Returns the cotangent of a number

COUNT Returns the number of records returned by a select query

DEGREES Converts a value in radians to degrees

DIV Used for integer division

EXP Returns e raised to the power of a specified number

FLOOR Returns the largest integer value that is <= to a number

GREATEST Returns thge greatest value of the list of arguments

LEAST Returns the s0mallest value of the list of arguments

LN Returns the natural logarithm of a number


LOG Returns the natural logarithm of a number, or the logarithm of a
specified base

LOG10 Returns the natural logarithm of a number to base 10

LOG2 Returns the natural logarithm of a number to base 2

MAX Returns the maximum value in a set of values

MIN Returns the minimum value in a set of values

MOD Returns the remainder of a number divided by another number

PI Returns the value of PI

POW Returns the value of a number raised to the power of another n

POWER Returns the() value of a number raised to the power of another

RADIANS Converts a degree value into radians

RAND Returns a random number

ROUND Rounds a number to a specified number of decimal places


SIGN Returns the sign of a number

SIN Returns the sine of a number

SQRT Returns the square root of a number

SUM Calculates the sum of a set of values

TAN Returns the tangent of a number

TRUNCATE Truncates a number to the specified number of decimal places

MySQL Date Functions


Function Description

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

CURDATE Returns the current date

CURRENT_DATE Returns the current date


CURRENT_TIME Returns the current time

CURRENT_TIMESTAMP Returns the current date and time

CURTIME Returns the current time

DATE Extracts the date part from a datetime expression

DATEDIFF Returns the number of days between two date values

DATE_ADD Adds a time/date interval to a date and then returns the date

DATE_FORMAT Formats a date

DATE_SUB Subtracts a time/date interval from a date and then returns the

DAY Returns the day of the month for a given date

DAYNAME Returns the weekday name for a given date

DAYOFMONTH Returns the day of the month for a given date


DAYOFWEEK Returns the weekday index for a given date

DAYOFYEAR Returns the day of the year for a given date

EXTRACT Extracts a part from a given date

FROM_DAYS Returns a date from a numeric datevalue

HOUR Returns the hour part for a given date

LAST_DAY Extracts the last day of the month for a given date

LOCALTIME Returns the current date and time

LOCALTIMESTAMP Returns the current date and time

MAKEDATE Creates and returns a date based on a year and a number of da

MAKETIME Creates and returns a time based on an hour, minute, and seco

MICROSECOND Returns the microsecond part of a time/datetime

MINUTE Returns the minute part of a time/datetime


MONTH Returns the month part for a given date

MONTHNAME Returns the name of the month for a given date

NOW Returns the current date and time

PERIOD_ADD Adds a specified number of months to a period

PERIOD_DIFF Returns the difference between two periods

QUARTER Returns the quarter of the year for a given date value

SECOND Returns the seconds part of a time/datetime

SEC_TO_TIME Returns a time value based on the specified seconds

STR_TO_DATE Returns a date based on a string and a format

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

SYSDATE Returns the current date and time


TIME Extracts the time part from a given time/datetime

TIME_FORMAT Formats a time by a specified format

TIME_TO_SEC Converts a time value into seconds

TIMEDIFF Returns the difference between two time/datetime expressions

TIMESTAMP Returns a datetime value based on a date or datetime value

TO_DAYS Returns the number of days between a date and date "0000-00

WEEK Returns the week number for a given date

WEEKDAY Returns the weekday number for a given date

WEEKOFYEAR Returns the week number for a given date

YEAR Returns the year part for a given date

YEARWEEK Returns the year and week number for a given date
MySQL Advanced Functions
Function Description

BIN Returns a binary representation of a number

BINARY Converts a value to a binary string

CASE Goes through conditions and return a value when the first cond

CAST Converts a value (of any type) into a specified datatype

COALESCE Returns the first non-null value in a list

CONNECTION_ID Returns the unique connection ID for the current connection

CONV Converts a number from one numeric base system to another

CONVERT Converts a value into the specified datatype or character set

CURRENT_USER Returns the user name and host name for the MySQL account t
server used to authenticate the current client

DATABASE Returns the name of the current database


IF Returns a value if a condition is TRUE, or another value if a con
FALSE

IFNULL Return a specified value if the expression is NULL, otherwise ret


expression

ISNULL Returns 1 or 0 depending on whether an expression is NULL

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

VERSION Returns the current version of the MySQL database

SELECT ADDTIME("2017-06-15 09:34:21", "2");--------------


SELECT ADDTIME("2017-06-15 09:34:21.000001", "5.000003");
SELECT ADDTIME("2017-06-15 09:34:21.000001", "2:10:5.000003");
SELECT ADDTIME("2017-06-15 09:34:21.000001", "5 2:10:5.000003");
SELECT ADDDATE("2017-06-15", INTERVAL 10 DAY);
SELECT ADDDATE("2017-06-15 09:34:21", INTERVAL 15 MINUTE);
SELECT ADDDATE("2017-06-15 09:34:21", INTERVAL -3 HOUR);
SELECT ADDDATE("2017-06-15", INTERVAL -2 MONTH);
SELECT CURDATE();

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");

SELECT OrderID, Quantity,


CASE
WHEN Quantity > 30 THEN “the quantity is greater than 30”
WHEN Quantity = 30 THEN "The quantity is 30"
ELSE "The quantity is under 30"
END
FROM OrderDetails;

Select first_name, job_id, salary,


Case when salary>100000 then “excellent”
When salary>80000 then “good”
When salary >50000 then “fair”
When salary >30000 then “satisfactory”
Else
“not okay”
From employees

Select stdid, stdname, stdmarks,


Case When stdmarks>70 then “passed”
Else “failed”
End as “status”
from student;
select stdid, stdname, stdmarks,
case when stdmarks>90 then “excellent”
when stdmarks>80 then “good”
when stdmarks>70 then ”satisfactory”
when stdmarks>60 then “pass”
else
“failed”
End as “status”
From student;

Select empid, empname,empsal,


Case When empsal>90000 then empsal*4/100
Else empsal*2/100
End as “tax”
from employee;

Select stdid, stdname, stdmarks,


Case when stdmarks >90 then “Excellent”
When stdmarks>80 then “good”
When stdmarks>70 then “satisfactory”
Else “the marks is less than 70”
End as grade
From student
Order by grade

Select empid, firstname, salary,


Case when salary >90000 then (salary*0.9)/100
When salary >80000 then (salary*0.5)/100
When salary >70000 then (salary*0.4)/100
Else “the salary is less than 70 no tax”
End
From Employee

SELECT CustomerName, City, Country


FROM Customers
ORDER BYexitexit

(CASE
WHEN City IS NULL THEN Country
ELSE City
END);

mysql> select position('a' in 'pavitra');


+----------------------------+
| position('a' in 'pavitra') |
+----------------------------+
| 2 |
+----------------------------+
1 row in set (0.02 sec)

mysql> create table student(st_id int primary key auto_increment,


-> st_name varchar(23) not null,
-> st_age int,
-> st_marks double,
-> st_city varchar(20)
-> );
Alter table student
auto_increment=300;
SELECT st_name, st_marks,
CASE
WHEN st_marks > 90 THEN "excellent"
WHEN st_marks > 70 THEN "Good"
When st_marks>60 then “fair”
ELSE "not qualified"
END
FROM student;

SELECT CAST("2017-08-29" AS DATE);

Int num=100;
Short s=(int)num;

SELECT CAST(150 AS CHAR);

Return the first non-null value in a list:

SELECT COALESCE(NULL, NULL, NULL, 'india', NULL, 'karnataka');

SELECT IF(500<1000, "YES", "NO");

SELECT IFNULL(NULL, "india");

SELECT IFNULL("Hello", "W3Schools.com");

SELECT IFNULL(NULL, 500);

SELECT ISNULL(NULL);

SELECT CustomerName, POSITION("a" IN CustomerName)


FROM Customers;
The MySQL LIMIT Clause
The LIMIT clause is used to specify the number of records to return.

The LIMIT clause is useful on large tables with thousands of records.


Returning a large number of records can impact performance.

LIMIT Syntax
SELECT column_name(s)
FROM table_name
WHERE condition
LIMIT number;

SELECT * FROM Customers


LIMIT 3;

SELECT * FROM Customers


WHERE Country='Germany'
LIMIT 3;

Constraints in mysql

Primary key----not accept null and duplicate


Unique key-----it accept the null value but doesn’t accept the
duplicate value
Not null-------it doesn’t accept null but accepts the duplicate
value
Foreign key----other table primary key will become the foreign
key of another table –referenced column
It accepts the values which are present in the primary key
column and accepts the duplicate values and null.
Check constraint---we are creating some condition on the column
Ex : age >22
Ex : LeaveTYPE ---sl, cl, ml, pl, prl
Default: default value for the specific column, value is almost
same for the all the record……
Create table department
(
Deptid int primary key auto_increment,
Deptname varchar(20) not null
)

Create table employee_details


(
Empid int primary key auto_increment,
Empname varchar(30) not null,
Salary double,
Email_id varchar(30) unique,
LeaveType char(5) check(leavetype in(‘sl’, ‘cl’, ‘pl’)),
Companyname varchar(20) default ‘Edubridge’,
Deptid int ,
constraint employee_dept_fk foreign key references
department( Deptid)
)
Alter table employee add prodid int
Alter table employee add constraint employee_product_fk foreign
key(prodid) references product(prodid) on delete cascade / on
delete null

Create table regions


(
Region_id int primary key auto_increment,
Region_name varchar(30) not null

Create table countries


(
Country_id int primary key auto_increment,
Country_name varchar(20) not null,
Region_id int,
Constraint country_region_fk foreign key(region_id) references
Regions(Region_id)
)

Single row functions --- abs , ascii, floor, ceil, round,


It accept one row as argument and returns one row as output
Lower()

Multiple row functions ---max,min,sum,count,average,


These functions accept more than one row as input
And produce one output.

Aggregate function, group functions..

Group by clause ---


Select columnname, groupfunction from tablename
Where
Group by columnname
Order by columnname

Create table studentdepartment


(
Deptid int primary key,
Deptname varchar(30) not null
)

SELECT MIN(column_name)
FROM table_name
WHERE condition;
SELECT MIN(Price) AS SmallestPrice
FROM Products;

SELECT MAX(Price) AS LargestPrice


FROM Products;

SELECT COUNT(ProductID)
FROM Products;

SELECT AVG(Price)
FROM Products;

SELECT SUM(Quantity)
FROM OrderDetails;

MySQL Joins---primary key


and foreign key
Inner join---common records present in both the tables
Left join---common records +uncommon records of left of table

Right join---common records +uncommon records of right of table

Cross join

Self Join

Empname, salary,deptid, deptid,deptname, deptlocation

100 suresh 12342.90 1000

200 satish 3456.90 3000

300 monalisha 89763.09 1000

400 kiran 15000.23 null

1000 hr Bangalore

2000 admin mysore

3000 devops Chennai


A JOIN clause is used to combine rows from two or more tables, based on a
related column between them.

Let's look at a selection from the "Orders" table:

OrderID CustomerID OrderDate

10308 2 1996-09-18

10309 37 1996-09-19

10310 77 1996-09-20

Then, look at a selection from the "Customers" table:

CustomerI CustomerNam ContactNam Country


D e e

1 Alfreds Maria Anders German


Futterkiste y

2 Ana Trujillo Ana Trujillo Mexico


Emparedados y
helados

3 Antonio Antonio Mexico


Moreno Moreno
Taquería
SELECT Orders.OrderID, Customers.CustomerName, Orders.OrderDate
FROM Orders
INNER JOIN Customers ON Orders.CustomerID=Customers.CustomerID;

SELECT S.ST_NAME, T.T_NAME,T.TRAINER_ID, S.TID


FROM STUDENT S
INNER JOIN TRAINER T
ON S.TID=T.TRAINER_ID

SELECT S.ST_NAME, T.T_NAME,T.TRAINER_ID, S.TID


FROM STUDENT S
LEFT JOIN TRAINER T
ON S.TID=T.TRAINER_ID

SELECT S.ST_NAME, T.T_NAME,T.TRAINER_ID, S.TID


FROM STUDENT S
RIGHT JOIN TRAINER T
ON S.TID=T.TRAINER_ID

SELECT S.ST_NAME, T.T_NAME, T.TRAINER_ID, S.TID,


T.TRAINER_ID,P.SID, P.PNAME
FROM TRAINER T
INNER JOIN STUDENT S
ON S.TID=T.TRAINER_ID

INNER JOIN PROJECT P


ON S.ST_ID=P.SID

Employee project
1 1

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);

 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.

INNER JOIN Syntax


SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name = table2.column_name;

Select e.first_name,e.last_name, d.deptname, e.salary,e.job_id


From employee e
Inner join
Department d
On(e.deptid=d.deptid) and
Where first_name not in (‘komal’);
// 1000 ==1000

Select d.deptname, dh.deptheadname


From department d
right join
Depthead dh
On(d.deptheadid = dh.deptheadid)

Select studentname, studentmarks,deptname


From student s
Inner join
Studentdepartment std
On s.deptid=std.deptid;

Select empname,salary, deptname


From employee e
Inner join department d
On e.deptid = d.deptid

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;

Select p.prid,p.pname,t.tid,s.trainer_id,t.tname, t.tspec,


s.s_name, s.s_marks
From trainer t
Inner join student s
On t.tid = s.trainer_id
Inner join project p
On p.prid=s.prid;
Demo Database
Below is a selection from the "Orders" table:

OrderID CustomerID EmployeeID OrderDate ShipperID

10308 2 7 1996-09-18 3

10309 37 3 1996-09-19 1

10310 77 8 1996-09-20 2

And a selection from the "Customers" table:

Custome CustomerNa ContactNa Address City PostalCo Countr


rID me me de y

1 Alfreds Maria Obere Str. Berlin 12209 Germa


Futterkiste Anders 57 ny

2 Ana Trujillo Ana Trujillo Avda. de Méxi 05021 Mexico


Emparedado la co
s y helados Constituci D.F.
ón 2222

3 Antonio Antonio Matadero Méxi 05023 Mexico


Moreno Moreno s 2312 co
Taquería D.F.
MySQL INNER JOIN Example
The following SQL statement selects all orders with customer information:

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!

JOIN Three Tables


The following SQL statement selects all orders with customer and shipper
information:

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);

MySQL LEFT JOIN Keyword


The LEFT JOIN keyword returns all records from the left table (table1), and the
matching records (if any) from the right table (table2).
LEFT JOIN Syntax
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name;

Select t.tid,s.trainer_id,t.tname, t.tspec, s.s_name, s.s_marks


From student s
right join trainer t
On t.tid = s.trainer_id

Demo Database
Below is a selection from the "Customers" table:

Customer CustomerNa ContactNa Address City PostalCo Countr


ID me me de y

1 Alfreds Maria Obere Str. Berlin 12209 Germa


Futterkiste Anders 57 ny

2 Ana Trujillo Ana Trujillo Avda. de Méxi 05021 Mexico


Emparedado la co
s y helados Constituci D.F.
ón 2222

3 Antonio Antonio Matadero Méxi 05023 Mexico


Moreno Moreno s 2312 co
Taquería D.F.

And a selection from the "Orders" table:

OrderI CustomerI EmployeeI OrderDat ShipperI


D D D e D

10308 2 7 1996-09- 3
18

10309 37 3 1996-09- 1
19

10310 77 8 1996-09- 2
20

MySQL LEFT JOIN Example


The following SQL statement will select all customers, and any orders they
might have:

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).

MySQL RIGHT JOIN Keyword


The RIGHT JOIN keyword returns all records from the right table (table2), and
the matching records (if any) from the left table (table1).

RIGHT JOIN Syntax


SELECT column_name(s)
FROM table1
RIGHT JOIN table2
ON table1.column_name = table2.column_name;

Demo Database
Below is a selection from the "Orders" table:

OrderI CustomerI EmployeeI OrderDat ShipperI


D D D e D

10308 2 7 1996-09- 3
18

10309 37 3 1996-09- 1
19
10310 77 8 1996-09- 2
20

And a selection from the "Employees" table:

EmployeeI LastNam FirstNam BirthDat Photo


D e e e

1 Davolio Nancy 12/8/196 EmpID1.p


8 ic

2 Fuller Andrew 2/19/195 EmpID2.p


2 ic

3 Leverlin Janet 8/30/196 EmpID3.p


g 3 ic

MySQL RIGHT JOIN Example


The following SQL statement will return all employees, and any orders they
might have placed:

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;

Self join------mapping table itself---

name Empid manid


rajshri 100 null
deji 101 100
komal 102 100
muthu 103 101
ajay 104 103
gokul 105 1000

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;

Select worker.last_name emp, worker.first_name empfirstname,


manager.last_name mgr, manager.first_name as manfirstName
From
employee worker
join employee manager
On (worker.manager_id=manager.empid);

Select worker.empname employeename, manager.empname managername


From
employee worker
join employee manager
On (worker.managerid=manager.empid);

Select emp.first_name employeename, m.first_name managername


From employee emp
Join
Employee m
On(emp.managerid=m.emp_id);

Where and having


Where ---to have condition on the fields(columns) which are
present in the table
Where name in (‘manisha’,’tanish’)

Having-----to apply the condition on the group by functions


Ex: count(*)>100
Avg(salary)>15000

Select e.first_name,e.salary, d.department_name


From employees e
Cross Join departments d

Join---used to join the two or more tables

Union---used to join the result of one or more queries

Select first_name,last_name from employees ----5


Select first_name,last_name from job_history;---3

Set Operators: Union, Union All

The MySQL UNION Operator


Union and join ----

The UNION operator is used to combine the result-set of two or


more SELECT statements.

 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;

UNION ALL Syntax


The UNION operator selects only distinct values by default. To allow duplicate
values, use UNION ALL:

SELECT column_name(s) FROM table1


UNION ALL
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:

Custome CustomerNa ContactNa Address City PostalCo Countr


rID me me de y

1 Alfreds Maria Obere Str. Berlin 12209 Germa


Futterkiste Anders 57 ny

2 Ana Trujillo Ana Trujillo Avda. de Méxi 05021 Mexico


Emparedado la co
s y helados Constituci D.F.
ón 2222

3 Antonio Antonio Matadero Méxi 05023 Mexico


Moreno Moreno s 2312 co
Taquería D.F.

And a selection from the "Suppliers" table:

SupplierI SupplierNa ContactNa Addres City PostalCod Countr


D me me s e y

1 Exotic Liquid Charlotte 49 Londo EC1 4SD UK


Cooper Gilbert n
St.

2 New Orleans Shelley P.O. New 70117 USA


Cajun Burke Box Orlean
Delights 78934 s
3 Grandma Regina 707 Ann 48104 USA
Kelly's Murphy Oxford Arbor
Homestead Rd.

SQL UNION Example


The following SQL statement returns the cities (only distinct values) from
both the "Customers" and the "Suppliers" 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!

SQL UNION ALL Example


The following SQL statement returns the cities (duplicate values also) from
both the "Customers" and the "Suppliers" table:

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;

SQL UNION ALL With WHERE


The following SQL statement returns the German cities (duplicate values
also) from both the "Customers" and the "Suppliers" table:

Example
SELECT City, Country FROM Customers
WHERE Country='Germany'
UNION ALL
SELECT City, Country FROM Suppliers
WHERE Country='Germany'
ORDER BY City;

Another UNION Example


The following SQL statement lists all customers and suppliers:

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

The MySQL GROUP BY Statement


The GROUP BY statement groups rows that have the same values into summary
rows, like "find the number of customers in each country".

The GROUP BY statement is often used with aggregate functions


(COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more
columns.

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

CustomerI CustomerName ContactName Address City PostalCode Country


D

1 Alfreds Maria Anders Obere Str. 57 Berlin 12209 Germany


Futterkiste

2 Ana Trujillo Ana Trujillo Avda. de la México 05021 Mexico


Emparedados y Constitución D.F.
helados 2222
3 Antonio Moreno Antonio Mataderos México 05023 Mexico
Taquería Moreno 2312 D.F.

MySQL GROUP BY Examples


The following SQL statement lists the number of customers in each country:

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

OrderI CustomerI EmployeeI OrderDat ShipperI


D D D e D
10248 90 5 1996-07- 3
04

10249 81 6 1996-07- 1
05

10250 34 4 1996-07- 2
08

And a selection from the "Shippers" table:

ShipperID ShipperName

1 Speedy Express

2 United Package

3 Federal Shipping

GROUP BY With JOIN Example


The following SQL statement lists the number of orders sent by each shipper:

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(CustomerID), Country


FROM Customers
GROUP BY Country
HAVING COUNT(CustomerID) > 5;
1-----india
2---aus
3---africa
4--india
5----aus
6---us

Select count(studentid),deptid
From student
Group by deptid
Having count(studentid)>5

SELECT COUNT(CustomerID), Country


FROM Customers GROUP BY Country
HAVING COUNT(CustomerID) > 5
ORDER BY COUNT(CustomerID) DESC;

Subquery: find the salary of employees who works along with


kochhar-same desgn as kochharn
Select salary from employees where job_id=(Select job_id from
employees where last_name=’Kochhar’);
Select salary from employees where job_id=(ad_vp);
Write a query to retrieve the information of employees who works
along with kochhar and who withdraw the same salary as king

Select *from employees Where job_id=(select job_id from employees


where last_name=’kochhar’) And salary=(select salary from
employees where last_name=’king’)

Select *From student where s_sem=(select s_sem from student where


s_name=’ganesh’);

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;

select *from student where s_marks=(select s_marks from students


where s_name in('tanu','mohan'));

where sname=’tanu’ and sname=’mohan’

display the employee details whose salary is greater than average


salary of the testing design or testing employees
select *From employee where salary=(select avg(salary) from
employee where design=’Testing’);

select *from student where s_marks=(select s_marks from student


where s_name = 'tanu') and s_marks=(select s_marks from student
where s_name = 'mohan');
 < = !=
in any all
<any >any
<all >all
Write query to diplay learners details those learners who is
scoring same marks as somu and mohan marks

Write query to diplay learners details those learners who scored


the marks less than either tanu and mohan marks

select *from student where s_marks=(select s_marks from student


where s_name in('tanu',’mohan’));

select *from student where s_marks=Any(select s_marks from


student where s_name in('tanu',’mohan’));

select *from student where s_marks>Any(80,79.39);


88<80 or 88<79.39
78.98<=80 78.98<=79
select *from student where s_marks>All(select s_marks from
student where s_name in('tanu',’mohan’));
greater than maximum
select *from student where s_marks>All(80,79.39)
88<80 and 88<79.39

Write query to display the learners who scores the marks is


lesser than average marks of 1 st department

Write query to display the learners who scores the marks is


lesser than average marks of their own department nisha
90/3---30 30/2--15
Nisha it 10
Asha cse 20 souter
Komal it 30
Satish cse 10
Nitish ece 15
Tanush ece 25
Ganesh it---50

10 < (10+30+50)/3 ==10<14.5


20<(30)/2==15.0 20<15.0

Select *from student souter where studentmarks<(select


avg(studentmarks) from student sinner where
souter.deptid=sinner.deptid)
//it =it
sinner
Nisha it 10 true
Asha cse 20 false
Komal it 30 true
Satish cse 10 f
Nitish ece 15 f
Tanush ece 25 f
Ganesh it---50 tru

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);

Select *from student sout where s_marks<(Select avg(s_marks) from


student sin where sout.deptid=sin.deptid)

Select s_name,s_marks,s_sem student sout where s_marks<(Select


avg(s_marks) from student sin where sout.s_sem=sin.s_sem)

Select s_name,s_marks, s_sem fromstudent sout where


s_marks<(select count(*) from student sin where
sout.s_id=sin.s_id);
= > < >= <= <> Single row operators
Any all in are the multiple row operators

Select learnes whose marks is greater than the avg marks of


learnes who stays in the city by name Mangalore
Select studentname,studentmarks from student where studentmarks>
(select avg(studentmarks) from student where city=’Mangalore’);

Select learnes whose marks is greater than the avg marks of


learnes based on their own city

Select studentname,studentmarks from student souter where


studentmarks> (select avg(studentmarks) from student sinner where
souter.city=sinner.city);

select first_name, last_name from employees


where job_id=(select job_id from employees where
first_name='praveen')
or
salary<(select salary from employees where first_name='praveen');
The MySQL ANY and ALL
Operators
The ANY and ALL operators allow you to perform a comparison between a
single column value and a range of other values.

The ANY Operator


The ANY operator:

 returns a boolean value as a result


 returns TRUE if ANY of the subquery values meet the condition

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 <=).

The ALL Operator


The ALL operator:

 returns a boolean value as a result


 returns TRUE if ALL of the subquery values meet the condition
 is used with SELECT, WHERE and HAVING statements

ALL means that the condition will be true only if the operation is true for all
values in the range.

ALL Syntax With SELECT


SELECT ALL column_name(s)
FROM table_name
WHERE condition;

ALL Syntax With WHERE or HAVING


SELECT column_name(s)
FROM table_name
WHERE column_name operator ALL
(SELECT column_name
FROM table_name
WHERE condition);

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 MySQL INSERT INTO SELECT


Statement
The INSERT INTO SELECT statement copies data from one table and inserts it
into another table.

The INSERT INTO SELECT statement requires that the data types in source and
target tables matches.

Note: The existing records in the target table are unaffected.

INSERT INTO SELECT Syntax


Copy all columns from one table to another table:

INSERT INTO table2


SELECT * FROM table1
WHERE condition;

Create table studentbackup


(
S_id int,
S_name varchar(25),
S_marks int,
S_sem int,
Trainer_id int,
Prid int
)

INSERT INTO Customers (CustomerName, City, Country)


SELECT SupplierName, City, Country FROM Suppliers;
The following SQL statement copies "Suppliers" into "Customers" (fill all
columns):

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.

Single Line Comments


Single line comments start with --.

Any text between -- and the end of the line will be ignored (will not be
executed).

The following example uses a single-line comment as an explanation:

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 */.

Any text between /* and */ will be ignored.

The following example uses a multi-line comment as an explanation:

Example
/*Select all the columns
of all the records
in the Customers table:*/
SELECT * FROM Customers;

The following example uses a multi-line comment to ignore many statements:

Example
/*SELECT * FROM Customers;
SELECT * FROM Products;
SELECT * FROM Orders;
SELECT * FROM Categories;*/
SELECT * FROM Suppliers;

To ignore just a part of a statement, also use the /* */ comment.

The following example uses a comment to ignore part of a line:

Example
SELECT CustomerName, /*City,*/ Country FROM Customers;

The following example uses a comment to ignore part of a statement:


Example
SELECT * FROM Customers WHERE (CustomerName LIKE 'L%'
OR CustomerName LIKE 'R%' /*OR CustomerName LIKE 'S%'
OR CustomerName LIKE 'T%'*/ OR CustomerName LIKE 'W%')
AND Country='USA'
ORDER BY CustomerName;

CREATE TABLE TestTable AS


SELECT customername, contactname
FROM customers;

MySQL CREATE INDEX Statement


The CREATE INDEX statement is used to create indexes in tables.

Select *From student where sid=500;//mysql engine primary index

Select *From student where sname=’savitha’;//manualy create the index—


secondary index

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.

Select *from employee where empid>4000

Update employee set first_name=’xyx’ where empid=1000;

Delete from employee where empid=2000;

CREATE INDEX Syntax


Creates an index on a table. Duplicate values are allowed:

CREATE INDEX index_name


ON table_name (column1, column2, ...);
CREATE UNIQUE INDEX Syntax
Creates a unique index on a table. Duplicate values are not allowed:

CREATE UNIQUE INDEX index_name


ON table_name (column1, column2, ...);

MySQL CREATE INDEX Example


The SQL statement below creates an index named "idx_lastname" on the
"LastName" column in the "Persons" table:

CREATE INDEX idx_lastname


ON Persons (LastName);

If you want to create an index on a combination of columns, you can list the
column names within the parentheses, separated by commas:

CREATE INDEX idx_pname


ON Persons (LastName, FirstName);

DROP INDEX Statement


The DROP INDEX statement is used to delete an index in a table.

ALTER TABLE table_name


DROP INDEX index_name;

What is an AUTO INCREMENT


Field?
Auto-increment allows a unique number to be generated automatically when
a new record is inserted into a table.

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.

By default, the starting value for AUTO_INCREMENT is 1, and it will increment by


1 for each new record.

The following SQL statement defines the "Personid" column to be an auto-


increment primary key field in the "Persons" table:

CREATE TABLE Persons (


Personid int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (Personid)
);

To let the AUTO_INCREMENT sequence start with another value, use the following
SQL statement:

ALTER TABLE Persons AUTO_INCREMENT=100;

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):

INSERT INTO Persons (FirstName,LastName)


VALUES ('Lars','Monsen');

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".

MySQL Date Data Types


MySQL comes with the following data types for storing a date or a date/time
value in the database:

 DATE - format YYYY-MM-DD


 DATETIME - format: YYYY-MM-DD HH:MI:SS
 TIMESTAMP - format: YYYY-MM-DD HH:MI:SS
 YEAR - format YYYY or YY

Note: The date data type are set for a column when you create a new table
in your database!

Working with Dates


Look at the following table:

Orders Table

OrderId ProductName OrderDate

1 Geitost 2008-11-11

2 Camembert Pierrot 2008-11-09

3 Mozzarella di Giovanni 2008-11-11

4 Mascarpone Fabioli 2008-10-29

Now we want to select the records with an OrderDate of "2008-11-11" from


the table above.

We use the following SELECT statement:

SELECT * FROM Orders WHERE OrderDate='2008-11-11'

The result-set will look like this:

OrderId ProductName OrderDate


1 Geitost 2008-11-11

3 Mozzarella di Giovanni 2008-11-11

Note: Two dates can easily be compared if there is no time component


involved!

Now, assume that the "Orders" table looks like this (notice the added time-
component in the "OrderDate" column):

OrderId ProductName OrderDate

1 Geitost 2008-11-11 13:23:44

2 Camembert Pierrot 2008-11-09 15:45:21

3 Mozzarella di Giovanni 2008-11-11 11:12:01

4 Mascarpone Fabioli 2008-10-29 14:56:59

If we use the same SELECT statement as above:

SELECT * FROM Orders WHERE OrderDate='2008-11-11'

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!

MySQL CREATE VIEW Statement


In SQL, a view is a virtual table based on the result-set of an SQL statement.

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.

A view is created with the CREATE VIEW statement.

CREATE VIEW Syntax


CREATE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Create view student_view as select stdid, stdname,stdmarks,
examdata, age
From student
Where age=21

Create view cmpview


as
Select e.emp_name, e.desig,e.salary, e.email_id, d.deptname
From employee e
Inner join
Department d
On(e.deptid=d.deptid);

Note: A view always shows up-to-date data! The database engine recreates
the view, every time a user queries it.

MySQL CREATE VIEW Examples


The following SQL creates a view that shows all customers from Brazil:

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

We can query the view above as follows:

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);

We can query the view above as follows:


Example
SELECT * FROM [Products Above Average Price];

MySQL Updating a View


A view can be updated with the CREATE OR REPLACE VIEW statement.

CREATE OR REPLACE VIEW Syntax


CREATE OR REPLACE VIEW view_name AS
SELECT column1, column2, ...
FROM table_name
WHERE condition;

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';

MySQL Dropping a View


A view is deleted with the DROP VIEW statement.

DROP VIEW Syntax


DROP VIEW view_name;

The following SQL drops the "Brazil Customers" view:

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.

How do I select everything after a specific character in SQL?

You can use the MySQL SUBSTRING_INDEX() function to return


everything before or after a certain character (or characters) in a string.
This function allows you to specify the delimiter to use, and you can specify
which one (in the event that there's more than one in the string).

How do I return a specific number of characters in SQL?

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

How do I slice a string in MySQL?


SUBSTRING() function in MySQL
1. string – Input String from which to extract.
2. start – The starting position. If it is a positive number, this function extracts from the
beginning of the string. ...
3. length – It is optional. It identifies the number of characters to extract.

What is position in MySQL?

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?

If you have phpMyAdmin installed use its 'Search' feature.


1. Select your DB.
2. Be sure you do have a DB selected (i.e. not a table, otherwise you'll get a completely
different search dialog)
3. Click 'Search' tab.
4. Choose the search term you want.
5. Choose the tables to search.

You might also like