Most Used MySQL Commands and Syntax

ยท

2 min read

MySQL is a relational database, which means that data is stored in tables.

  • Tables are made up of rows and columns.
  • Rows represent individual records, and columns represent individual pieces of data for each record.
  • MySQL uses SQL (Structured Query Language) to interact with the database.
  • SQL is a powerful language that can be used to create, read, update, and delete data in a database.

Here's a basic MySQL cheat sheet that includes commonly used commands and syntax:

Creating a database:

CREATE DATABASE database_name;

Switching to a database:

USE database_name;

Creating a table:

CREATE TABLE table_name (
  column1 datatype constraint,
  column2 datatype constraint,
  ...
);

Adding a primary key constraint:

ALTER TABLE table_name ADD PRIMARY KEY (column_name);

Adding a foreign key constraint:

ALTER TABLE table_name ADD FOREIGN KEY (column_name) REFERENCES referenced_table(ref_column);

Inserting data into a table:

INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...);

Updating data in a table:

UPDATE table_name SET column = new_value WHERE condition;

Deleting data from a table:

DELETE FROM table_name WHERE condition;

Retrieving all rows from a table:

SELECT * FROM table_name;

Retrieving specific columns from a table:

SELECT column1, column2, ... FROM table_name;

Applying conditions to a SELECT statement:

SELECT * FROM table_name WHERE condition;

Sorting data:

SELECT * FROM table_name ORDER BY column ASC/DESC;

Joining tables:

SELECT * FROM table1 JOIN table2 ON table1.column = table2.column;

Aggregating data using GROUP BY:

SELECT column, COUNT(*) FROM table_name GROUP BY column;

Applying filters to aggregated data using HAVING:

SELECT column, COUNT(*) FROM table_name GROUP BY column HAVING condition;

Creating an index on a column:

CREATE INDEX index_name ON table_name (column);

Dropping a table:

DROP TABLE table_name;

Dropping a database:

DROP DATABASE database_name;

Remember to replace database_name, table_name, column_name, etc., with your actual database, table, and column names.

ย