0% found this document useful (0 votes)
60 views25 pages

MYSQL Definations

Uploaded by

karunasreem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
60 views25 pages

MYSQL Definations

Uploaded by

karunasreem
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Create Database

SHOW DATABASES Statement

Syntax

SHOW {DATABASES | SCHEMAS}


[LIKE 'pattern' | WHERE expr]

SHOW DATABASES lists the databases on the MySQL server host. SHOW SCHEMAS is a synonym for SHOW
DATABASES. The LIKE clause, if present, indicates which database names to match. The WHERE clause can be given
to select rows using more general conditions

You see only those databases for which you have some kind of privilege, unless you have the global SHOW
DATABASES privilege

Exapmle :

SHOW DATABASES;

+----------+
| Database |
+----------+
| mysql |
| test |
| tmp |
+----------+

SHOW TABLES;

SHOW DATABASES lists the table on the current database

Example:

Show Tables:

+----------+
| Tables |
+----------+
| Employee |
| Movies |
| Directos |
+----------+

Create Table :

CREATE TABLE creates a table with the given name

Syntax

CREATE TABLE [IF NOT EXISTS] tbl_name


(create_definition,...)
[table_options]
[partition_options]

Table Name

 tbl_name
The table name can be specified as db_name.tbl_name to create the table in a specific database. This works
regardless of whether there is a default database, assuming that the database exists.

IF NOT EXISTS

Prevents an error from occurring if the table exists.

Table Cloning and Copying

 LIKE
Use CREATE TABLE ... LIKE to create an empty table based on the definition of another table, including any
column attributes and indexes defined in the original table:
CREATE TABLE new_tbl LIKE orig_tbl;

 [AS] query_expression
To create one table from another, add a SELECT statement at the end of the CREATE TABLE statement:

CREATE TABLE new_tbl AS SELECT * FROM orig_tbl;

data_type

data_type represents the data type in a column definition

NOT NULL | NULL

If neither NULL nor NOT NULL is specified,


the column is treated as though NULL had been specified.

Syntax

column_name data_type NOT NULL;

Example

CREATE TABLE tasks (


id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
start_date DATE NOT NULL,
end_date DATE
);
Alter not null

Syntax

ALTER TABLE table_name


CHANGE
old_column_name
new_column_name column_definition;

Example

ALTER TABLE tasks


CHANGE
end_date
end_date DATE NOT NULL;

Drop a NOT NULL constraint

1 ALTER TABLE table_name


2 MODIFY column_name column_definition;

Exmple

ALTER TABLE tasks


MODIFY
end_date
end_date DATE Null;

DEFAULT

Specifies a default value for a column.

There is two types of default values

1. Implicit: MySQL automatically sets a default value if not provided.

For numeric data types, the default is 0. If a column is declared as an integer and with the AUTO_INCREMENT
attribute, the default is the next value in the sequence.

2. Explicit: We can explicitly set a DEFAULT value when creating or altering a table

Syntax:
CREATE TABLE table_name(
column_name data_type,
Column_name data_type DEFAULT ‘value’
);

Example

CREATE TABLE Employee (


Employee_ID int NOT NULL,
Last_Name varchar(255) NOT NULL,
First_Name varchar(255),
Age int,
Location varchar(255) DEFAULT 'London',
Joining_Date DATETIME
);

Set DEFAULT value on ALTER TABLE


ALTER TABLE table_name
ALTER column_name SET DEFAULT 'value';
Example

Alter table Employee alter Joining_date set default ’01-Jan-2018’

Drop Default Constraint

ALTER TABLE TableNmae ALTER Column DROP DEFAULT;

Example

Alter table Employee alter Joining_date Drop default ;

AUTO_INCREMENT

An integer or floating-point column can have the additional attribute AUTO_INCREMENT.

When you insert a value of NULL (recommended) or 0 into an indexed AUTO_INCREMENT column, the column is
set to the next sequence value.
Syntax

CREATE TABLE table_name


(
column1 datatype NOT NULL AUTO_INCREMENT,
column2 datatype [ NULL | NOT NULL ],
...
);

By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record.

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

ALTER TABLE Persons AUTO_INCREMENT=100;

With no argument, LAST_INSERT_ID() returns a BIGINT UNSIGNED (64-bit) value representing the first
automatically generated value successfully inserted for an AUTO_INCREMENT column as a result of the most
recently executed INSERT statement. The value of LAST_INSERT_ID() remains unchanged if no rows are successfully
inserted.

If you insert multiple rows using a single INSERT statement, LAST_INSERT_ID() returns the value generated for
the first inserted row only. The reason for this is to make it possible to reproduce easily the
same INSERT statement against some other server.

SELECT LAST_INSERT_ID();

CONSTRAINTS

The CONSTRAINT symbol clause may be given to name a constraint. If the clause is not given, or a symbol is not
included following the CONSTRAINT keyword, MySQL automatically generates a constraint name.
PRIMARY KEY

A unique index where all key columns must be defined as NOT NULL. If they are not explicitly declared as NOT
NULL, MySQL declares them so implicitly (and silently). A table can have only one PRIMARY KEY. The name of
a PRIMARY KEY is always PRIMARY, which thus cannot be used as the name for any other kind of index.

Syntax:

CREATE TABLE table_name


(
column1 column_definition,
column2 column_definition,
...

CONSTRAINT [constraint_name]
PRIMARY KEY (column1, column2, ... column_n)
);

Example

CREATE TABLE contacts

( contact_id INT(11) NOT NULL AUTO_INCREMENT,

last_name VARCHAR(30) NOT NULL,

first_name VARCHAR(25),

birthday DATE,

CONSTRAINT contacts_pk PRIMARY KEY (contact_id)

);

Alter Primary Key


Syntax
ALTER TABLE table_name
ADD CONSTRAINT [ constraint_name ]
PRIMARY KEY [ USING BTREE | HASH ] (column1, column2, ... column_n)

Exmple
ALTER TABLE contacts
ADD CONSTRAINT contacts_pk
PRIMARY KEY (contact_id);

Drop Primary key


Syntax
ALTER TABLE table_name
DROP PRIMARY KEY;

Exmple
ALTER TABLE contacts
DROP PRIMARY KEY;

UNIQUE

A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to
add a new row with a key value that matches an existing row. For all engines, a UNIQUE index permits
multiple NULL values for columns that can contain NULL. If you specify a prefix value for a column in
a UNIQUE index, the column values must be unique within the prefix length.

Syntax

CREATE UNIQUE INDEX index_name


ON table_name(index_column_1,index_column_2,...);

Example

CREATE TABLE IF NOT EXISTS contacts (


id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50) NOT NULL,
last_name VARCHAR(50) NOT NULL,
phone VARCHAR(15) NOT NULL,
email VARCHAR(100) NOT NULL,
UNIQUE KEY unique_email (email)
);

Drop a unique constraint

To drop a UNIQUE constraint, you use can use DROP INDEX or ALTER TABLE statement:

Syntax

DROP INDEX index_name ON table_name;


ALTER TABLE table_name
DROP INDEX index_name;

Example

DROP INDEX unique_email ON contacts;

Add new unique constraint

The following ALTER TABLE ADD CONSTRAINT adds a unique constraint to a column of an existing table:

Syntax:

ALTER TABLE table_name ADD CONSTRAINT constraint_name UNIQUE (column_list);

This statement adds a UNIQUE constraint uc_name_address back to the suppliers table:

ALTER TABLE contacts ADD CONSTRAINT uc_name_address UNIQUE (phone, email);

Foreign Key:

A foreign key is a column or group of columns in a table that links to a column or group of columns in another
table. The foreign key places constraints on data in the related tables, which allows MySQL to maintain referential
integrity.

Syntax

[CONSTRAINT constraint_name]
FOREIGN KEY [foreign_key_name] (column_name, ...)
REFERENCES parent_table(colunm_name,...)

Example

CREATE TABLE categories(


categoryId INT AUTO_INCREMENT PRIMARY KEY,
categoryName VARCHAR(100) NOT NULL
) ENGINE=INNODB;
CREATE TABLE products(
productId INT AUTO_INCREMENT PRIMARY KEY,
productName varchar(100) not null,
categoryId INT,
CONSTRAINT fk_category
FOREIGN KEY (categoryId)
REFERENCES categories(categoryId)
) ENGINE=INNODB;

Drop Foreign key

ALTER TABLE table_name


DROP FOREIGN KEY constraint_name;

Example

ALTER TABLE products


DROP FOREIGN KEY fk_category;

Select

SELECT is used to retrieve rows selected from one or more tables

Syntax:

SELECT [DISTINCT|ALL ] { * | [fieldExpression [AS newName]} FROM tableName [alias] [WHERE condition][GROUP
BY fieldName(s)] [HAVING condition] ORDER BY fieldName(s)

Example

Select 1+1;
2

Select 1+1 from Dual;

DUAL is purely for the convenience of people who require that all SELECT statements should have FROM and
possibly other clauses

Distinct

MySQL DISTINCT clause is used to remove duplicate records from the table and fetch only the unique records. The
DISTINCT clause is only used with the SELECT statement.

Syntax

SELECT DISTINCT expressions


FROM tables
[WHERE conditions];

Order By

The MYSQL ORDER BY Clause is used to sort the records in ascending or descending order.

Syntax

SELECT expressions
FROM tables
[WHERE conditions]
ORDER BY expression [ ASC | DESC ];

If you use MySQL ORDER BY clause without specifying the ASC and DESC modifier then by default you will get
the result in ascending order

Group By
The MYSQL GROUP BY Clause is used to collect data from multiple records and group the result by one or more
column. It is generally used in a SELECT statement.

You can also use some aggregate functions like COUNT, SUM, MIN, MAX, AVG etc. on the grouped column.

Syntax

SELECT expression1, expression2, ... expression_n,


aggregate_function (expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n;

Aggregate Functions

Count

The MySQL count() function is used to return the count of an expression. It is used when you need to count some
records of your table.

Syntax

SELECT COUNT (aggregate_expression)


FROM table_name
[WHERE conditions];

Sum

The MySQL sum() function is used to return the total summed value of an expression.

SELECT SUM(aggregate_expression)
FROM tables
[WHERE conditions];

AVG

The MySQL avg() function is used to return the average value of an expression.

Syntax

SELECT AVG(aggregate_expression)
FROM tables
[WHERE conditions];

MIN

The MySQL min() function is used to return the minimum value from the table.

Syntax
SELECT MIN (aggregate_expression)
FROM tables
[WHERE conditions];

MAX

The MySQL max() function is used to return the maximum value of an expression. It is used when you need to get
the maximum value from your table.

Syntax

SELECT MAX(aggregate_expression)
FROM tables
[WHERE conditions];

Limit

Limit clause used to select first record or more.

Syntax

SELECT column_name
FROM table_name
LIMIT 1;

If you want last record

Syntax

SELECT column_name
FROM table_name
ORDER BY column_name DESC
LIMIT 1;

Having

MySQL HAVING Clause is used with GROUP BY clause. It always returns the rows where condition is TRUE.

Syntax

SELECT expression1, expression2, ... expression_n,


aggregate_function (expression)
FROM tables
[WHERE conditions]
GROUP BY expression1, expression2, ... expression_n
HAVING condition;

Example

SELECT emp_name, SUM(working_hours) AS "Total working hours"


FROM employees
GROUP BY emp_name
HAVING SUM(working_hours) > 5;

AND
The MySQL AND condition is used with SELECT, INSERT, UPDATE or DELETE statements to test two or more
conditions in an individual query.

Syntax

WHERE condition1
AND condition2
...
AND condition_n;

Example

SELECT * FROM Movies WHERE MovieName = 'Ratri' AND DirectorId =1;

OR
The MySQL OR condition specifies that if you take two or more conditions then one of the conditions must be
fulfilled to get the records as result.

Syntax
WHERE condition1
OR condition2
...
OR condition_n;

Example

SELECT * FROM Movies WHERE MovieName = 'Ratri' or DirectorId =1;

AND OR

In MySQL, you can use AND & OR condition both together with the SELECT, INSERT, UPDATE and DELETE
statement. While combine these conditions, you must be aware where to use round brackets so that the database
know the order to evaluate each condition.

Syntax

WHERE condition1
AND condition2
...
OR condition_n;

Example
SELECT *
FROM Movies
WHERE (Moviename = 'SATYA' or MovieName = 'SHIVA')
and (Directorid = 1);

LIKE

In MySQL, LIKE condition is used to perform pattern matching to find the correct result. It is used in SELECT,
INSERT, UPDATE and DELETE statement with the combination of WHERE clause.

Syntax
expression LIKE pattern [ ESCAPE 'escape_character' ]
Example

SELECT *
FROM Movies
WHERE Moviename LIKE 'M%';

Using _(Underscore)

Example

SELECT *
FROM Movies
WHERE Moviename LIKE 'SH_VA';

Using NOT

SELECT *
FROM Movies
WHERE Moviename not LIKE 'M%';

IN

The MySQL IN condition is used to reduce the use of multiple OR conditions in a SELECT, INSERT, UPDATE and
DELETE statement

Syntax
expression IN (value1, value2, .... value_n);

Example

SELECT *
FROM Movies
WHERE Moviename IN(‘RATHRI’,’SHIVA’);

NOT

The MySQL NOT condition is opposite of MySQL IN condition. It is used to negate a condition in a SELECT, INSERT,
UPDATE or DELETE statement.
Syntax

NOT condition
Example

SELECT *
FROM Movies
WHERE Moviename Not IN (‘RATHRI’,’SHIVA’);

SELECT *
FROM Movies
WHERE Moviename not LIKE 'M%';

SELECT *
FROM Movies
WHERE Directorid NOT BETWEEN 3 AND 5;

NULL

MySQL IS NULL condition is used to check if there is a NULL value in the expression. It is used with SELECT, INSERT,
UPDATE and DELETE statement.

Syntax
expression IS NULL
Example

SELECT *
FROM Movies
WHERE Moviename IS NULL;

Not Null

MySQL IS NOT NULL condition is used to check the NOT NULL value in the expression. It is used with SELECT,
INSERT, UPDATE and DELETE statements.

Syntax

expression IS NOT NULL

Example

SELECT *
FROM Movies
WHERE Moviename IS not NULL;

Between
The MYSQL BETWEEN condition specifies how to retrieve values from an expression within a specific range. It is
used with SELECT, INSERT, UPDATE and DELETE statement.

Syntax

expression BETWEEN value1 AND value2;

Example

SELECT *
FROM Movies
WHERE Directorid BETWEEN 1 AND 3;

JOINS

MySQL JOINS are used with SELECT statement. It is used to retrieve data from multiple tables. It is performed
whenever you need to fetch records from two or more tables.

There are three types of MySQL joins:

o MySQL INNER JOIN (or sometimes called simple join)


o MySQL LEFT OUTER JOIN (or sometimes called LEFT JOIN)
o MySQL RIGHT OUTER JOIN (or sometimes called RIGHT JOIN)

INNER JOIN

The MySQL INNER JOIN is used to return all rows from multiple tables where the join condition is satisfied.
It is the most common type of join.

Syntax
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;

Example

SELECT *
FROM Movies
INNER JOIN Directors
ON Movies.Directorid = Directors.d;

Left Outer Join


The LEFT OUTER JOIN returns all rows from the left hand table specified in the ON condition and only those rows
from the other table where the join condition is fulfilled.

Syntax

SELECT columns
FROM table1
LEFT [OUTER] JOIN table2
ON table1.column = table2.column;
Right Outer Join

The MySQL Right Outer Join returns all rows from the RIGHT-hand table specified in the ON condition and only
those rows from the other table where he join condition is fulfilled.

Syntax
SELECT columns
FROM table1
RIGHT [OUTER] JOIN table2
ON table1.column = table2.column;

Indexes

A database index is a data structure that improves the speed of operations in a table. Indexes can be created using
one or more columns, providing the basis for both rapid random lookups and efficient ordering of access to
records.

The INSERT and UPDATE statements take more time on tables having indexes, whereas the SELECT statements
become fast on those tables. The reason is that while doing insert or update, a database needs to insert or update
the index values as well.

If a table contains no primary key, InnoDB automatically promotes the first UNIQUE NOT NULL index
to the primary key.

Syntax

CREATE INDEX index_name ON table_name ( column1, column2,...);

Example
create index Name_index on employee(emp_name);
ALTER
Syntax
ALTER TABLE tablename ADD INDEX Index_Name (Column1,….);

Example
alter table employee add index Dept_index (Deptid);

Drop Index
alter table tablename drop index index_Name;

Example
alter table employee drop index name_index;

Displaying Index

Syntax

SHOW INDEX FROM Table_name;

Example

SHOW INDEX FROM employee;

Functions
In MySQL, a function is a stored program that you can pass parameters into and then return a
value.

A routine is considered “deterministic” if it always produces the same result for the same input
parameters, and “not deterministic” otherwise. If neither DETERMINISTIC nor NOT
DETERMINISTIC is given in the routine definition, the default is NOT DETERMINISTIC. To
declare that a function is deterministic, you must specify DETERMINISTIC explicitly.

Syntax
DELIMITER $$

CREATE FUNCTION function_name(


param1,
param2,…
)
RETURNS datatype
[NOT] DETERMINISTIC
BEGIN
-- statements
END $$
DELIMITER ;

Example

DELIMITER //
CREATE FUNCTION Employee_Details ( Name Varchar(50), City varchar(50) )
RETURNS varchar(100)
DETERMINISTIC
BEGIN
RETURN concat('Name :', Name, 'City : ', City);
END; //
DELIMITER ;

Calling Function

Syntax
Select Function_Name (Parameters);

Example:
select Employee_Details(emp_name,city) from employee;

Drop Function

Syntax

Drop Function Function_Name;

Example
Drop function Employee_Details;
Example

DELIMITER $$

CREATE FUNCTION CustomerLevel(


credit DECIMAL(10,2)
)
RETURNS VARCHAR(20)
DETERMINISTIC
BEGIN
DECLARE customerLevel VARCHAR(20);

IF credit > 50000 THEN


SET customerLevel = 'PLATINUM';
ELSEIF (credit >= 50000 AND
credit <= 10000) THEN
SET customerLevel = 'GOLD';
ELSEIF credit < 10000 THEN
SET customerLevel = 'SILVER';
END IF;
-- return the customer level
RETURN (customerLevel);
END$$
DELIMITER ;

Create New User

Syntax

CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';

Example
CREATE USER 'AJAY'@'localhost' IDENTIFIED BY '502ajay';

GRANT

Syntax
GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';
Example

GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';

FLUSH PRIVILEGES;
GRANT Permissions to particular database

Syntax
GRANT ALL ON DAtabaseName.* TO 'UserName'@'localhost';

Example
GRANT ALL ON Sample.* TO 'AJAY'@'localhost';

Grant a Select Query


Syntax
GRANT SELECT ON Database.TableName TO 'USER'@'localhost';

Example
GRANT SELECT ON Sample.Employee TO 'AJAY'@'localhost';

ALTER Previllages

ALTER USER 'AJAY'@'localhost' WITH MAX_QUERIES_PER_HOUR 90;

show grants;

Drop user

DROP USER 'AJAY'@'localhost';

GRANT SELECT, INSERT, UPDATE ON *.* TO 'AJAY'@'localhost';


REVOKE INSERT, UPDATE ON *.* FROM 'AJAY'@'localhost';

Privilege Meaning and Grantable Levels


ALL [PRIVILEGES] Grant all privileges at specified access level except GRANT OPTION and PROXY.
ALTER Enable use of ALTER TABLE. Levels: Global, database, table.
Enable stored routines to be altered or dropped. Levels: Global, database,
ALTER ROUTINE routine.
Privilege Meaning and Grantable Levels
CREATE Enable database and table creation. Levels: Global, database, table.
CREATE ROLE Enable role creation. Level: Global.
CREATE ROUTINE Enable stored routine creation. Levels: Global, database.
CREATE Enable tablespaces and log file groups to be created, altered, or dropped. Level:
TABLESPACE Global.
CREATE TEMPORARY
TABLES Enable use of CREATE TEMPORARY TABLE. Levels: Global, database.
Enable use of CREATE USER, DROP USER, RENAME USER, and REVOKE ALL
CREATE USER PRIVILEGES. Level: Global.
CREATE VIEW Enable views to be created or altered. Levels: Global, database, table.
DELETE Enable use of DELETE. Level: Global, database, table.
Enable databases, tables, and views to be dropped. Levels: Global, database,
DROP table.
DROP ROLE Enable roles to be dropped. Level: Global.
EVENT Enable use of events for the Event Scheduler. Levels: Global, database.
EXECUTE Enable the user to execute stored routines. Levels: Global, database, routine.
FILE Enable the user to cause the server to read or write files. Level: Global.
Enable privileges to be granted to or removed from other accounts. Levels:
GRANT OPTION Global, database, table, routine, proxy.
INDEX Enable indexes to be created or dropped. Levels: Global, database, table.
INSERT Enable use of INSERT. Levels: Global, database, table, column.
Enable use of LOCK TABLES on tables for which you have the SELECT privilege.
LOCK TABLES Levels: Global, database.
PROCESS Enable the user to see all processes with SHOW PROCESSLIST. Level: Global.
PROXY Enable user proxying. Level: From user to user.
REFERENCES Enable foreign key creation. Levels: Global, database, table, column.
RELOAD Enable use of FLUSH operations. Level: Global.
REPLICATION
CLIENT Enable the user to ask where master or slave servers are. Level: Global.
REPLICATION Enable replication slaves to read binary log events from the master. Level:
SLAVE Global.
SELECT Enable use of SELECT. Levels: Global, database, table, column.
SHOW DATABASES Enable SHOW DATABASES to show all databases. Level: Global.
SHOW VIEW Enable use of SHOW CREATE VIEW. Levels: Global, database, table.
SHUTDOWN Enable use of mysqladmin shutdown. Level: Global.
Enable use of other administrative operations such as CHANGE MASTER
TO, KILL, PURGE BINARY LOGS, SET GLOBAL, and mysqladmin
SUPER debug command. Level: Global.
TRIGGER Enable trigger operations. Levels: Global, database, table.
UPDATE Enable use of UPDATE. Levels: Global, database, table, column.
USAGE Synonym for “no privileges”
Views

Views are stored queries that when invoked produce a result set. A view acts as a virtual table.

Syntax

CREATE [OR REPLACE] VIEW [db_name.]view_name [(column_list)]


AS
select-statement;

Example

create view vw_Employee as


select eMP_NAME, DeptName from Employee, department Where Deptid = department.ID;

select* FROM vw_Employee;

You might also like