The command throughout the article is divided into the following categories
User management commands are those commands which create users for them to access the database and perform various actions. The commands are:
With the help of this command, you can create users in the database server.
CREATE USER AccountName IDENTIFIED BY 'PASSWORD';
CREATE USER SahitiKappagantula IDENTIFIED BY 'InfoEdge@123';
Used to delete a user from the database server permanently.
DROP USER AccountName;
DROP USER SahitiKappagantula;
Used to display the list of users having access to a particular database server.
SELECT USER from MYSQL.DATABASENAME;
SELECT USER from MYSQL.Patients;
Database management commands are those commands which are used to create a database and view them. The commands are:
Must read: What are the Advantages of DBMS?
Used to create a database.
CREATE SCHEMA SchemaName;
CREATE SCHEMA PatientsDatabase;
Used to list all the databases created till date.
SHOW DATABASES; -–OR SHOW SCHEMAS;
SHOW DATABASES;
Also read: What are the Applications of DBMS?
Used to delete a database along with the data present in the database.
DROP SCHEMA SchemaName; –OR DROP DATABASE DatabaseName;
DROP SCHEMA PatientsDatabase; DROP DATABASE PatientsDatabase;
Used by the clients to inform which database to be chosen to perform all data manipulation tasks.
USE SchemaName;
USE PatientsDatabase;
Once the database is created, the next step is to create tables to build relations between them and generate meaningful insights. So, in the next section of MySQL Commands, let us understand the table commands.
In this section of commands, let us understand the various commands used to create tables and manipulate data in the tables. The following commands will be discussed here:
Used to create a new table in a database.
CREATE TABLE TableName ( Column1 Datatype, Column2 Datatype, Column3 Datatype, .... );
CREATE TABLE Patients ( PatientID int, PatientName varchar(255), Sex varchar(255), Age int, Address varchar(255), PostalCode int, State varchar(255), Country varchar(255), RegDate date );
Used to create a new table from an existing table.
CREATE TABLE NewTableName AS SELECT Column1, Column2,... FROM ExistingTableName WHERE ....;
CREATE TABLE SamplePatientsTable AS SELECT PatientID, PatientName, Age FROM Patients;
Used to list all the tables created in a database. Here, please note that you have to use the database first before displaying the database
SHOW TABLES;
USE PatientsDatabase; SHOW TABLES;
Used to manipulate columns or constraints by addition, modification or deletion.
ALTER TABLE TableName ADD ColumnName datatype;
ALTER TABLE Patients ADD INT BP;
Used to display the structure of the tables. It will display the column names, their data types, default values, and keys.
DESCRIBE TableName;
DESCRIBE Patients;
Used to delete the data present in the tables, without deleting the table.
TRUNCATE TABLE TableName;
TRUNCATE TABLE Patients;
Used to delete a table including its data permanently.
DROP TABLE TableName;
DROP TABLE Patients;
Used to rename a table.
RENAME TABLE TableName1 TO TableName2;
RENAME TABLE Patients TO PatientsInfo;
Used to insert new records into a table.
INSERT INTO TableName (Column1, Column2, ...) VALUES (Value1, Value2,...); --OR INSERT INTO TableName VALUES (Value1, Value2);
INSERT INTO Patients ( PatientID,PatientName,Sex,Age,Address,PostalCode,State,Country,RegDate date ) VALUES ('06', 'Suhana','F', ‘12’, 'House No 34C Jubilee Hills', '500046', ‘Telangana’, 'India', ‘02/09/2021’); –OR INSERT INTO Patients VALUES ('06', 'Suhana','F', ‘12’, 'House No 34C Jubilee Hills', '500046', ‘Telangana’, 'India', ‘02/09/2021’);
Used to modify the existing data items in a table.
UPDATE TableName SET column1 = value1, column2 = value2, ... WHERE condition;
UPDATE Patients SET PatientName = 'Afsana', PostalCode= '500034' WHERE PatientID = 1;
Used to delete the existing data items in a table.
DELETE FROM TableName WHERE condition;
DELETE FROM Patients WHERE PatientName='Anay';
Used to add new columns in a table.
ALTER TABLE TableName ADD COLUMN NewColumnName ColumnDataType; –OR –To add after a particular column ALTER TABLE TableName ADD COLUMN NewColumnName ColumnDataType AFTER ColumnName; –OR –To add multiple columns ALTER TABLE TableName ( ADD COLUMN NewColumnName ColumnDataType AFTER ColumnName, ADD COLUMN NewColumnName ColumnDataType AFTER ColumnName );
ALTER TABLE Patients ADD COLUMN BP int; –OR –To add after a particular column ALTER TABLE Patients ADD COLUMN BP int AFTER Age; –OR –To add multiple columns ALTER TABLE TableName ( ADD COLUMN BP int AFTER Age, ADD COLUMN Weight int AFTER BP);
Used to delete columns from a table.
ALTER TABLE TableName DROP COLUMN ColumnName; –OR –To drop multiple columns ALTER TABLE TableName ( DROP COLUMN ColumnName, DROP COLUMN ColumnName);
ALTER TABLE Patients ADD COLUMN BP int; –OR –To add after a particular column ALTER TABLE Patients ADD COLUMN BP int AFTER Age; –OR –To add multiple columns ALTER TABLE TableName ( ADD COLUMN BP int AFTER Age, ADD COLUMN Weight int AFTER BP);
Used to display all the columns present in the database.
SHOW COLUMNS FROM TableName FROM DatabaseName; --OR SHOW COLUMNS FROM DatabaseName.TableName;
SHOW COLUMNS FROM Patients FROM PatientsDatabase; --OR SHOW COLUMNS FROM PatientsDatabase.Patients;
Used to rename columns present in a table.
ALTER TABLE TableName CHANGE COLUMN OldColumnName NewColumnName DataType; --OR –To change multiple column names with CHANGE query ALTER TABLE TableName ( CHANGE COLUMN OldColumnName NewColumnName DataType, CHANGE COLUMN OldColumnName NewColumnName DataType); --OR ALTER TABLE TableName RENAME COLUMN OldColumnName TO NewColumnName; --OR –To change multiple column names with RENAME query ALTER TABLE TableName ( RENAME COLUMN OldColumnName TO NewColumnName, RENAME COLUMN OldColumnName TO NewColumnName );
ALTER TABLE Patients CHANGE COLUMN Address PatientAddress VARCHAR(255); --OR To change multiple column names with CHANGE query ALTER TABLE Patients ( CHANGE COLUMN Address PatientAddress VARCHAR(255), CHANGE COLUMN BP PatientBP INT); —OR ALTER TABLE Patients RENAME COLUMN Address TO PatientAddress; –OR ALTER TABLE Patients ( RENAME COLUMN Address TO PatientAddress, RENAME COLUMN BP TO PatientBP);
Multiple tables are uniquely identified with the help of the various keys present in the tables. These keys help the users build relationships between multiple tables.
The following are 5 different types of keys used commonly.
A set of attributes that can uniquely identify a tuple. A single relation in the database can have multiple candidate keys, which can either be a simple or composite key.
A set of attributes that can uniquely identify a tuple is known as Super Key. You should know that a candidate key is a superkey, but a super key is not a candidate key isn’t true.
A set of attributes that can be used to uniquely identify every tuple is a primary key. If there are multiple candidate keys present in a relationship, out of those, only one can be chosen as a primary key.
CREATE TABLE TableName ( Column1 Datatype, Column2 Datatype PRIMARY KEY, Column3 Datatype, .... );
CREATE TABLE Patients ( PatientID int PRIMARY KEY, PatientName varchar(255), Sex varchar(255), Age int, Address varchar(255), PostalCode int, State varchar(255), Country varchar(255), RegDate date );
All the candidate keys other than the primary key are called alternate keys.
Attributes that can only take the data values present as the value of some other attribute are known as the foreign key to the attribute to which it refers.
CREATE TABLE TableName ( Column1 Datatype, Column2 Datatype PRIMARY KEY, Column3 Datatype, CONSTRAINT FKeyName FOREIGN KEY (CurrenTableColumn) REFERENCES ParentTableColumn .... );
CREATE TABLE Doctors ( DoctorID int PRIMARY KEY, DoctorName varchar(255), CONSTRAINT DocPatient FOREIGN KEY (DoctorID) REFERENCES PatientID );
Constraints are used in the database to enforce certain data rules while creating tables. They are also used to check values in the database. The most popular constraints are:
Make sure all the data values in that particular column are unique. More than one column can have the UNIQUE constraint
CREATE TABLE TableName ( Column1 Datatype, Column2 Datatype UNIQUE, Column3 Datatype, .... );
CREATE TABLE Patients ( PatientID int UNIQUE, PatientName varchar(255), Sex varchar(255), Age int, Address varchar(255), PostalCode int, State varchar(255), Country varchar(255), RegDate date );
Make sure that no null value can be stored in a column of a table. More than one column can have the NOT NULL constraint
CREATE TABLE TableName ( Column1 Datatype, Column2 Datatype NOT NULL, Column3 Datatype, .... );
CREATE TABLE Patients ( PatientID int NOT NULL, PatientName varchar(255), Sex varchar(255) NOT NULL, Age int, Address varchar(255), PostalCode int, State varchar(255), Country varchar(255), RegDate date );
Make sure that all the values in a column satisfy the mentioned condition
CREATE TABLE TableName ( Column1 Datatype, Column2 Datatype CHECK (Column2 Condition), Column3 Datatype, .... );
CREATE TABLE Patients ( PatientID int, PatientName varchar(255), Sex varchar(255, Age int CHECK (Age >=20), Address varchar(255), PostalCode int, State varchar(255), Country varchar(255), RegDate date );
Make sure that the mentioned default value is taken automatically when no value is specified for that data record.
CREATE TABLE TableName ( Column1 Datatype, Column2 Datatype DEFAULT DefaultValue, Column3 Datatype, .... );
CREATE TABLE Patients ( PatientID int, PatientName varchar(255), Sex varchar(255), Age int DEFAULT ‘0’, Address varchar(255), PostalCode int, State varchar(255), Country varchar(255), RegDate date );
Views are used to create a virtual table based on the output of the SQL query given by the users.
Views have a similar outlook as that of a table. They have rows and columns and can have data fields from multiple tables in the database.
Used to create a view from single or multiple tables.
CREATE VIEW ViewName AS SELECT Column1, Column2, … FROM TableName WHERE Condition;
CREATE VIEW Kids ( PatientID int,PatientName varchar(255),Sex varchar(255),Age int FROM Patients WHERE Age <=18; );
A view can be updated by using the CREATE OR REPLACE VIEW command.
CREATE OR REPLACE VIEW ViewName AS SELECT Column1, Column2, … FROM TableName WHERE Condition;
CREATE OR REPLACE VIEW Kids ( PatientID int,PatientName varchar(255),Sex varchar(255),Age int FROM Patients WHERE Age <=18; );
Used to delete a view.
DROP VIEW ViewName;
DROP VIEW Kids;
Next in this MySQL commands article, let us understand the data manipulation commands.
Data Manipulation commands are used to manipulate, alter and update the data according to the client requirements. The commands in this section are:
Used to select a set of data points from a database. It stores the data returned as output in the result set.
SELECT column1, column2, ... FROM TableName; --(*)-> select all from the table SELECT * FROM TableName;
SELECT PatientName, State FROM Patients; SELECT * FROM Patients;
MySQL Clauses used with the SELECT statement are as follows:
Used to filter the data by mentioning conditions. This clause is generally used with the SELECT, INSERT, UPDATE, and DELETE commands.
SELECT column1, column2, ... FROM TableName WHERE Conditions;
SELECT PatientName, State FROM Patients WHERE Age > 20;
Used to return only the distinct values from a dataset.
SELECT DISTINCT Column1, Column2, ... FROM TableName;
SELECT DISTINCT State FROM Patients;
Used to retrieve data from a table.
SELECT Column1, Column2, ... FROM TableName;
SELECT PatientID, State FROM Patients;
Used to sort the results in an ascending or descending order. Here, you should know that by default, the results are sorted in ascending order. If you wish to sort the data in descending order, then you have to use the DESC keyword.
SELECT Column1, Column2, ... FROM TableName ORDER BY Column1, Column2, ... DESC;
SELECT * FROM Patients ORDER BY Age; SELECT * FROM Patients ORDER BY Age DESC; SELECT * FROM Patients ORDER BY Age, PatientName; SELECT * FROM Patients ORDER BY Age DESC, PatientName ASC;
Most commonly used with the aggregate functions to group the output by one or more columns.
SELECT Column1, Column2, ... FROM TableName WHERE Conditions GROUP BY Column1, Column2, ..., ORDER BY Column1, Column2, ... DESC;
SELECT COUNT(PatientID), State FROM Patients GROUP BY State ORDER BY COUNT(PatientID);
Used with the aggregate functions to mention conditions, and filter data.
SELECT Column1, Column2, ... FROM TableName WHERE Conditions GROUP BY Column1, Column2, ..., HAVING Conditions ORDER BY Column1, Column2, ...;
SELECT COUNT(PatientID), State FROM Patients GROUP BY State ORDER BY COUNT(Age) > 40;
This section of MySQL commands consists of the various conditional operators used to manipulate data. Commands covered in this section of the article are as follows:
Used to filter records based on one or more conditions. It displays all those records that satisfy all the conditions separated by AND and generates an output as TRUE.
SELECT Column1, Column2, ... FROM TableName WHERE Condition1 AND Condition2 ...;
SELECT * FROM Patients WHERE State='Telangana' AND Age > 23;
Used to filter records that satisfy either of the conditions and generate output as TRUE.
SELECT Column1, Column2, ... FROM TableName WHERE Condition1 OR Condition2 ...;
SELECT * FROM Patients WHERE State='Telangana' OR Age > 23;
Used to display those records which do not satisfy a condition.
SELECT Column1, Column2, ... FROM TableName WHERE NOT Condition;
SELECT * FROM Patients WHERE NOT State='Telangana';
Used to select values from a given range.
SELECT Column1, Column2, ... FROM TableName WHERE ColumnName BETWEEN Value1 AND Value2;
SELECT * FROM Patients WHERE Age BETWEEN 15 AND 18;
Most commonly used in a WHERE clause to search for a pattern in a column of a table with the help of wildcards.
SELECT Column1, Column2, ... FROM TableName WHERE ColumnName LIKE Pattern;
SELECT * FROM Patients WHERE PatientName LIKE ‘A%’;
Used to mention NULL as a value for a single column or multiple columns.
SELECT Column1, Column2, ... FROM TableName WHERE ColumnName IS NULL;
SELECT * FROM Patients WHERE State IS NULL;
Used to restrict a single column or multiple columns having NULL values.
SELECT Column1, Column2, ... FROM TableName WHERE ColumnName IS NOT NULL;
SELECT * FROM Patients WHERE State IS NOT NULL;
Used to specify multiple values in a WHERE clause.
SELECT Column1, Column2, ... FROM TableName WHERE ColumnName IN (Value1, Value2, . . .);
SELECT * FROM Patients WHERE State IN (‘Rajasthan’, ‘Telangana’);
Used to test if the required record exists or not.
SELECT Column1, Column2, ... FROM TableName WHERE EXISTS (SELECT ColumnName FROM TableName WHERE Conditions);
Used with a WHERE or HAVING clause to return all the records which meet conditions.
SELECT Column1, Column2, ... FROM TableName WHERE ColumnName Operator ALL (SELECT ColumnName FROM TableName WHERE Conditions);
SELECT PatientName FROM Patients WHERE PatientID = ALL (SELECT PatientID FROM Patients WHERE Age < 35);
Used with a WHERE or HAVING clause to return only those records which meet conditions.
SELECT Column1, Column2, ... FROM TableName WHERE ColumnName Operator ANY (SELECT ColumnName FROM TableName WHERE Conditions);
SELECT PatientName FROM Patients WHERE PatientID = ANY (SELECT PatientID FROM Patients WHERE BETWEEN 20 AND 35);
Used for returning a set of rows that are not equal.
SELECT Column1, Column2, ... FROM TableName, WHERE ColumnName <> Conditions; –OR SELECT Column1, Column2, ... FROM TableName, WHERE ColumnName != Conditions;
SELECT PatientName FROM Patients WHERE Age <> ‘35’; –OR SELECT PatientName FROM Patients WHERE Age != ‘35’;
Aggregate functions as the name suggests, help the users perform simple operations in MySQL as follows
Used to return the addition of a numeric column from a table.
SELECT SUM(ColumnName) FROM TableName;
SELECT SUM(Age) FROM Patients;
Used to return the average value of a numeric column from a table.
SELECT AVG(ColumnName) FROM TableName;
SELECT AVG(Age) FROM Patients;
Used to return the smallest value from a column of a table.
SELECT MIN(ColumnName) FROM TableName;
SELECT MIN(Age) FROM Patients;
Used to return the largest value from a column of a table.
SELECT MAX(ColumnName) FROM TableName;
SELECT MAX(Age) FROM Patients;
Used to return the count of elements in a column of a table.
SELECT COUNT(ColumnName) FROM TableName;
SELECT COUNT(Age) FROM Patients;
Used to return the first value of a column from a table.
SELECT ColumnName FROM TableName LIMIT 1; –Select first 3 records SELECT ColumnName FROM TableName LIMIT 3;
SELECT PatientID, Age FROM Patients LIMIT 1; – Select first 3 records SELECT PatientID, Age FROM Patients LIMIT 3;
Used to return the last value of a column from a table.
SELECT ColumnName FROM TableName ORDER BY ColumnName DESC LIMIT 1;
SELECT PatientID, Age FROM Patients ORDER BY PatientID DESC LIMIT 1;
There are three set operations used on a daily basis in manipulating databases. They are:
Used to combine the output of two or more SELECT queries. Here, you should remember that the data types and the number of columns must be the same. Also, once the rows are combined, the UNION operation removes duplicate rows.
SELECT ColumnName FROM Table1 UNION SELECT ColumnName FROM Table2;
SELECT PatientID FROM Patients UNION SELECT PatientID FROM Patients2;
Used to combine the output of two or more SELECT queries. Here, you should remember that the data types and the number of columns must be the same. Also, once the rows are combined, the UNION ALL operation DOES NOT remove duplicate rows.
SELECT ColumnName FROM Table1 UNION ALL SELECT ColumnName FROM Table2;
SELECT PatientID FROM Patients UNION ALL SELECT PatientID FROM Patients2;
Used to return the common records from two or more SELECT queries. Here, you should remember that the data types and the number of columns must be the same. Also, the INTERSECT operation will sort the data in ascending order automatically.
SELECT ColumnName FROM Table1 INTERSECT SELECT ColumnName FROM Table2;
SELECT PatientID FROM Patients INTERSECT SELECT PatientID FROM Patients2;
Used to return rows either from the first query and not return the second query.
SELECT ColumnName FROM Table1 MINUS SELECT ColumnName FROM Table2;
SELECT PatientID FROM Patients MINUS SELECT PatientID FROM Patients2;
JOINS in MySQL are used to combine records from two or more tables, based on a relationship between tables. Let’s consider the following table apart from the above Patients table, to understand the syntax of joins.
Returns all records from the left table along with all the records from the right table, which satisfy the condition.
SELECT Column1, Column2 …(s) FROM Table1 LEFT JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;
SELECT Diseases.DiseaseID, Patients.PatientName FROM Diseases LEFT JOIN Patients ON Diseases.PatientID = Patients.PatientID ORDER BY Diseases.DiseaseID;
Returns all records from the right table along with all the records from the left table, which satisfy the condition.
SELECT Column1, Column2 …(s) FROM Table1 RIGHT JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;
SELECT Diseases.DiseaseID, Patients.PatientName FROM Diseases RIGHTJOIN Patients ON Diseases.PatientID = Patients.PatientID ORDER BY Diseases.DiseaseID;
Returns records that have matching values in both the tables.
SELECT Column1, Column2 …(s) FROM Table1 INNER JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;
SELECT Diseases.DiseaseID, Patients.PatientName FROM Diseases INNER JOIN Patients ON Diseases.PatientID = Patients.PatientID;
Returns records that either have a match in the left or the right table.
SELECT Column1, Column2 …(s) FROM Table1 FULL OUTER JOIN Table2 ON Table1.ColumnName = Table2.ColumnName;
SELECT Diseases.DiseaseID, Patients.PatientName FROM Diseases FULL OUTER JOIN Patients ON Diseases.PatientID = Patients.PatientID;
Moving further with the SQL commands, let us understand the
Indexes are lookup tables used to retrieve data. An index as the name suggests acts as a pointer to the data present in the table.
Used to create an index for a table.
CREATE INDEX IndexName ON TableName;
CREATE INDEX SampleIndex ON Patients;
Used to alter an index
ALTER INDEX IndexName ON ObjectName;
ALTER INDEX SampleIndex ON PatName;
Used to delete or remove an index
DROP INDEX IndexName;
DROP INDEX SampleIndex;
The Data Control commands are used to control the privileges of a database. The commands are:
Used to provide users with the privileges for a database.
GRANT Privileges ON Objects TO user;
GRANT CREATE ANY TABLE TO localhost;
Used to withdraw the privileges given to the users.
REVOKE privileges ON object FROM user;
REVOKE INSERT ON *.* FROM Patients;
Triggers are a set of SQL statements that are invoked automatically in response to an event. Every trigger, associated with a table, is activated by DML commands such as INSERT, UPDATE, and DELETE.
There are two types of triggers:
Used to create a trigger in MySQL.
CREATE TRIGGER TriggerName (AFTER | BEFORE) (INSERT | UPDATE | DELETE) ON TableName FOR EACH ROW BEGIN --Declarations --Trigger Code END;
Transaction commands deal with all the transactions related to the database. The commands are:
Used to save all the transactions of the database since the last COMMIT or ROLLBACK command.
COMMIT;
DELETE FROM Patients WHERE Age > 45; COMMIT;
ROLLBACK;
Used to undo all the transactions since the last COMMIT or ROLLBACK.
DELETE FROM Patients WHERE Age > 45; ROLLBACK;
Used to roll the transaction back to a certain point without actually rolling back the entire transaction.
--Save the SAVEPOINT SAVEPOINT SAVEPOINTNAME; --Rollback to the Savepoint ROLLBACK TO SAVEPOINTNAME;
SAVEPOINT EX1; DELETE FROM Patients WHERE Age > 45; SAVEPOINT EX2;
Used to remove a SAVEPOINT created previously.
RELEASE SAVEPOINT SAVEPOINTNAME;
RELEASE SAVEPOINT EX1;
Used to give a name to the transaction.
SET TRANSACTION [ READ WRITE | READ ONLY ];
ARTICULO ORIGINAL AQUÍ: https://www.shiksha.com/online-courses/articles/most-popular-mysql-commands/
Duplicates in single column
---------------------------
SELECT
col,
COUNT(col)
FROM
table_name
GROUP BY col
HAVING COUNT(col) > 1;
Duplicates in multiple columns
------------------------------
SELECT
col1, COUNT(col1),
col2, COUNT(col2),
...
FROM
table_name
GROUP BY
col1,
col2, ...
HAVING
(COUNT(col1) > 1) AND (COUNT(col2) > 1)
Show max allowed packet (extend in 50-server.conf when get error "Got an error reading communication packets")
------------------------
SHOW VARIABLES LIKE 'max_allowed_packet';
Get databases sizes in Mb
------------------------
SELECT table_schema AS 'DB Name', ROUND(SUM(data_length + index_length) / 1024 / 1024, 1) AS 'DB Size in MB' FROM information_schema.tables GROUP BY table_schema;