Tag: MySQL

  • MySQL CLI Quick Reference

    Connecting to MySQL

    • Login to MySQL:
      mysql -u username -p

    Prompts for a password.

    • Specify Database on Login:
      mysql -u username -p -D database_name

    Basic Commands

    • Show all databases:
      SHOW DATABASES;
    • Select a database:
      USE database_name;
    • Show all tables in the current database:
      SHOW TABLES;
    • Describe the structure of a table:
      DESCRIBE table_name;
    • Show the current MySQL user:
      SELECT USER();
    • Show current database:
      SELECT DATABASE();
    • Show process list:
      SHOW PROCESSLIST;
    • Show full process list (to see full queries):
      SHOW FULL PROCESSLIST;
    • Exit MySQL:
      EXIT;

    CRUD Operations

    • Create a new database:
      CREATE DATABASE database_name;
    • Create a new table:
      CREATE TABLE table_name (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(100),
        age INT
      );
    • Insert data into a table:
      INSERT INTO table_name (name, age) VALUES ('John', 30);
    • Select data from a table:
      SELECT * FROM table_name;
    • Update data in a table:
      UPDATE table_name SET age = 31 WHERE name = 'John';
    • Delete data from a table:
      DELETE FROM table_name WHERE name = 'John';
    • Drop a table:
      DROP TABLE table_name;

    Loading .sql Files

    To load and execute an SQL file that contains queries or database structure (e.g., schema.sql or data.sql):

    Method 1: From Inside the MySQL Prompt
    1. Open MySQL:
       mysql -u username -p
    1. Select the database you want to load the file into:
       USE database_name;
    1. Load the SQL file:
       SOURCE /path/to/your/file.sql;
    Method 2: Directly from the Command Line

    You can execute the SQL file directly from the command line without entering the MySQL prompt:

    mysql -u username -p database_name < /path/to/your/file.sql

    This method runs the .sql file directly into the specified database.

    Common Tips

    • View running MySQL queries:
      Use SHOW FULL PROCESSLIST; to view running queries, especially helpful for debugging long-running queries.
    • Check MySQL version:
      SELECT VERSION();
    • Enable SQL logging:
      Use SET GLOBAL general_log = 'ON'; to start logging all queries. To view the log, check the path from the following:
      SHOW VARIABLES LIKE 'general_log_file';

    These commands and tips should help you navigate MySQL efficiently!

  • MySQL Query Cheat Sheet

    -- Create a new database
    -- This creates a new database named "sandbox". This is not necessary if you already have a database to work with.
    CREATE DATABASE database_name;
    
    -- Use a specific database
    -- This selects the "sandbox" database for use. Replace "sandbox" with the name of the database you want to use.
    USE database_name;
    
    -- Create a new table
    -- This creates a new table named "table_name" with columns "column1" and "column2" of data types "datatype1" and "datatype2" respectively. Replace "table_name", "column1", "column2", "datatype1", and "datatype2" with the desired names and data types.
    CREATE TABLE table_name (
        column1 datatype,
        column2 datatype,
        ...
    );
    
    -- Insert data into a table
    -- This inserts a new row into the "table_name" table with values "value1" and "value2" for columns "column1" and "column2" respectively. Replace "table_name", "column1", "column2", "value1", and "value2" with the desired table name, column names, and values.
    INSERT INTO table_name (column1, column2, ...)
    VALUES (value1, value2, ...);
    
    -- Select all rows from a table
    -- This selects all rows from the "table_name" table. Replace "table_name" with the name of the table you want to select from.
    SELECT * FROM table_name;
    
    -- Select specific columns from a table
    -- This selects specific columns "column1" and "column2" from the "table_name" table. Replace "column1", "column2", and "table_name" with the desired column names and table name.
    SELECT column1, column2, ... FROM table_name;
    
    -- Filter rows using WHERE clause
    -- This selects all rows from the "table_name" table where the condition is met. Replace "table_name" with the name of the table you want to select from and "condition" with the desired condition.
    SELECT * FROM table_name WHERE condition;
    
    -- Update data in a table
    -- This updates the "column1" and "column2" columns in the "table_name" table with new values "value1" and "value2" where the condition is met. Replace "table_name", "column1", "column2", "value1", "value2", and "condition" with the desired table name, column names, values, and condition.
    UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;
    
    -- Delete data from a table
    -- This deletes rows from the "table_name" table where the condition is met. Replace "table_name" with the name of the table you want to delete from and "condition" with the desired condition.
    DELETE FROM table_name WHERE condition;
    
    -- Join two or more tables
    -- This joins the "table1" and "table2" tables on the "column" column. Replace "table1", "table2", and "column" with the names of the tables and column you want to join on.
    SELECT * FROM table1 JOIN table2 ON table1.column = table2.column;
    
    -- Order rows in ascending or descending order
    -- This selects all rows from the "table_name" table and orders them in ascending or descending order based on the "column" column. Replace "table_name" and "column" with the name of the table and column you want to order by, and "ASC" or "DESC" with the desired order.
    SELECT * FROM table_name ORDER BY column ASC/DESC;
    
    -- Limit the number of rows returned
    -- This selects the first "number" rows from the "table_name" table. Replace "table_name" with the name of the table you want to select from and "number" with the desired number of rows.
    SELECT * FROM table_name LIMIT number;
    
    -- Group rows and perform aggregate functions
    -- This groups rows in the "table_name" table by the "column" column and counts the number of rows in each group. Replace "table_name" and "column" with the name of the table and column you want to group by.
    SELECT column, COUNT(*) FROM table_name GROUP BY column;
    
    -- Create an index on a table
    -- This creates an index named "index_name" on the "column" column in the "table_name" table. Replace "index_name", "table_name", and "column" with the desired index name, table name, and column.
    CREATE INDEX index_name ON table_name (column);
    
    -- Drop a table
    -- This drops the "table_name" table. Replace "table_name" with the name of the table you want to drop. This is a destructive operation and cannot be undone.
    DROP TABLE table_name;
    
    -- Drop a database
    -- This drops the "database_name" database. Replace "database_name" with the name of the database you want to drop. This is a destructive operation and cannot be undone.
    DROP DATABASE database_name;
    
    -- Show all databases
    SHOW DATABASES;
    
    -- Show all tables in a database
    SHOW TABLES;
    
    -- Show the structure of a table
    -- This shows the columns, data types, and other information about the "table_name" table. Replace "table_name" with the name of the table you want to show the structure of.
    DESC table_name;
    
    -- Show the indexes on a table
    -- This shows the indexes on the "table_name" table. Replace "table_name" with the name of the table you want to show the indexes of.
    SHOW INDEX FROM table_name;
    
    -- Show the status of the server
    -- This shows various status information about the server, such as the number of connections, queries, and other statistics.
    SHOW STATUS;
    
    -- Show the current user
    SELECT USER();
    
    -- Show the current database
    SELECT DATABASE();
    
    -- Show the version of MySQL
    SELECT VERSION();
    
    -- Show the current date and time
    SELECT NOW();
    
    -- Show the current time zone
    SELECT @@time_zone;
    
    -- Join two or more tables
    -- This joins the "table1" and "table2" tables on the "column" column.
    -- A join combines rows from two or more tables based on a related column between them.
    SELECT * FROM table1 JOIN table2 ON table1.column = table2.column;
    
    -- Left join two or more tables
    -- This left joins the "table1" and "table2" tables on the "column" column.
    -- A left join returns all rows from the left table and the matched rows from the right table.
    SELECT * FROM table1 LEFT JOIN table2 ON table1.column = table2.column;
    
    -- Right join two or more tables
    -- This right joins the "table1" and "table2" tables on the "column" column.
    -- A right join returns all rows from the right table and the matched rows from the left table.
    SELECT * FROM table1 RIGHT JOIN table2 ON table1.column = table2.column;
    
    -- Full outer join two or more tables
    -- This full outer joins the "table1" and "table2" tables on the "column" column.
    -- A full outer join returns all rows when there is a match in either the left or right table.
    SELECT * FROM table1 FULL OUTER JOIN table2 ON table1.column = table2.column;
    
    -- Cross join two or more tables
    -- This cross joins the "table1" and "table2" tables.
    -- A cross join returns the Cartesian product of the two tables, i.e., all possible combinations of rows.
    SELECT * FROM table1 CROSS JOIN table2;
    
    
    MySQL Query Cheat Sheet
  • WordPress: How to manually create a user in the database

    Manually creating a WordPress user in the database involves adding a new entry to the wp_users table and assigning the necessary user capabilities. Here are the steps to do this:

    Please exercise caution when making direct changes to your WordPress database, as incorrect changes can break your site. Make sure to back up your database before proceeding.

    1. Access Your Database:
      Log in to your server or hosting provider’s control panel and access the phpMyAdmin or a similar tool to manage your WordPress database.
    2. Find the wp_users Table:
      In phpMyAdmin, look for your WordPress database on the left-hand side and click to select it. Then, find and click on the wp_users table.
    3. Insert a New User:
      Click the “Insert” or “Add” tab (the exact label may vary depending on your phpMyAdmin version). This will open a form for adding a new row to the wp_users table.
    4. Fill in User Information:
      Fill in the following fields for the new user:
    • user_login: Enter the desired username for the new user.
    • user_pass: Generate a secure password hash. You can use online tools to create password hashes or use WordPress’s built-in wp_hash_password function. Make sure to select the MD5 option when entering the password hash.
    • user_nicename: This can be the same as the user_login.
    • user_email: Enter the email address for the new user.
    • user_registered: Set the registration date in the format “YYYY-MM-DD HH:MM:SS”.
    • display_name: The display name for the user.
    1. Insert the User:
      Click the “Go” or “Insert” button to insert the new user into the wp_users table.
    2. Assign Capabilities:
      To assign capabilities to the user, you’ll need to find the user’s ID in the wp_users table (it’s typically an auto-incremented number) and then add an entry in the wp_usermeta table.
    • Go to the wp_usermeta table.
    • Insert a new row with the following values:
      • user_id: The ID of the new user from the wp_users table.
      • meta_key: Enter wp_capabilities.
      • meta_value: Insert a serialized array with the user’s capabilities. For example, to make the user an administrator, you can use a:1:{s:13:"administrator";b:1;}.
    1. Login to WordPress:
      You should now be able to log in to your WordPress site using the credentials you provided.

    Please be extremely careful when making changes directly to the database, and ensure that you have a backup in case anything goes wrong. It’s recommended to use the WordPress admin interface to create and manage users whenever possible to avoid potential issues.

    WordPress: How to manually create a user in the database
  • Update WordPress MySQL tables from old domain name to new domain name

    This code is typically used when migrating a WordPress site from one domain to another, ensuring that all references to the old domain are updated to the new domain.

    /*
    This SQL code block updates various tables in a WordPress database to replace occurrences of the 'Old_Domain_Name' with the 'New_Domain_Name'. The specific tables being updated are:
    - wp_options: Updates the option_value column for rows where the option_name is 'home' or 'siteurl'.
    - wp_posts: Updates the post_content column.
    - wp_postmeta: Updates the meta_value column.
    - wp_usermeta: Updates the meta_value column.
    - wp_links: Updates the link_url column.
    - wp_comments: Updates the comment_content column.
    */
    
    UPDATE wp_options SET option_value = replace(option_value, 'Old_Domain_Name','New_Domain_Name') WHERE option_name = 'home' OR option_name = 'siteurl';
    
    UPDATE wp_posts SET post_content = replace(post_content, 'Old_Domain_Name','New_Domain_Name');
    
    UPDATE wp_postmeta SET meta_value = replace(meta_value,'Old_Domain_Name','New_Domain_Name');
    
    UPDATE wp_usermeta SET meta_value = replace(meta_value, 'Old_Domain_Name','New_Domain_Name');
    
    UPDATE wp_links SET link_url = replace(link_url, 'Old_Domain_Name','New_Domain_Name');
    
    UPDATE wp_comments SET comment_content = replace(comment_content , 'Old_Domain_Name','New_Domain_Name');
    Update WordPress MySQL tables from old domain name to new domain name