MYSQL Definations
MYSQL Definations
Syntax
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;
Example:
Show Tables:
+----------+
| Tables |
+----------+
| Employee |
| Movies |
| Directos |
+----------+
Create Table :
Syntax
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
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:
data_type
Syntax
Example
Syntax
Example
Exmple
DEFAULT
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
Example
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
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:
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:
CONSTRAINT [constraint_name]
PRIMARY KEY (column1, column2, ... column_n)
);
Example
first_name VARCHAR(25),
birthday DATE,
);
Exmple
ALTER TABLE contacts
ADD CONSTRAINT contacts_pk
PRIMARY KEY (contact_id);
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
Example
To drop a UNIQUE constraint, you use can use DROP INDEX or ALTER TABLE statement:
Syntax
Example
The following ALTER TABLE ADD CONSTRAINT adds a unique constraint to a column of an existing table:
Syntax:
This statement adds a UNIQUE constraint uc_name_address back to the suppliers table:
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
Example
Select
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
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
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
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
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
Syntax
SELECT column_name
FROM table_name
LIMIT 1;
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
Example
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
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
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
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
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.
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;
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
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
Example
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 $$
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
Example
Drop function Employee_Details;
Example
DELIMITER $$
Syntax
Example
CREATE USER 'AJAY'@'localhost' IDENTIFIED BY '502ajay';
GRANT
Syntax
GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';
Example
FLUSH PRIVILEGES;
GRANT Permissions to particular database
Syntax
GRANT ALL ON DAtabaseName.* TO 'UserName'@'localhost';
Example
GRANT ALL ON Sample.* TO 'AJAY'@'localhost';
Example
GRANT SELECT ON Sample.Employee TO 'AJAY'@'localhost';
ALTER Previllages
show grants;
Drop user
Views are stored queries that when invoked produce a result set. A view acts as a virtual table.
Syntax
Example