What is SQL?

  • SQL is the standard language for dealing with Relational Databases.
  • MySQL is a widely used relational database management system (RDBMS).
  • SQL is used to insert, search, update, and delete database records.
  • Some database systems require a semicolon at the end of each SQL statement.
  • Semicolon is the standard way to separate each SQL statement in database systems that allow more than one SQL statement to be executed in the same call to the server.
  • Example:
    SELECT * FROM Customers;
    selects all the records in the "Customers" table
  • Some of The Most Important SQL Commands
    • SELECT - extracts data from a database
    • UPDATE - updates data in a database
    • DELETE - deletes data from a database
    • INSERT INTO - inserts new data into a database
    • CREATE DATABASE - creates a new database
    • ALTER DATABASE - modifies a database
    • CREATE TABLE - creates a new table
    • ALTER TABLE - modifies a table
    • DROP TABLE - deletes a table
    • CREATE INDEX - creates an index (search key)
    • DROP INDEX - deletes an index

Create a new SQL database

  • The CREATE DATABASE statement is used to create a new SQL database.
  • Syntax:
    CREATE DATABASE databasename;

Drop an existing SQL database

  • The DROP DATABASE statement is used to drop an existing SQL database.
  • Syntax:
    DROP DATABASE databasename;

Create a new table

  • The CREATE TABLE statement is used to create a new table in a database.
  • Syntax:
                  
      CREATE TABLE table_name (
        column1 datatype,
        column2 datatype,
        column3 datatype,
        ....
      );
                  
                
  • Example:
                  
      CREATE TABLE Persons (
        PersonID int,
        LastName varchar(255),
        FirstName varchar(255),
        Address varchar(255),
        City varchar(255)
      );
                  
                
    The LastName, FirstName, Address, and City columns are of type varchar and will hold characters, and the maximum length for these fields is 255 characters.

Create Table Using Another Table

  • A copy of an existing table can also be created using CREATE TABLE.
  • The new table gets the same column definitions. All columns or specific columns can be selected.
  • If you create a new table using an existing table, the new table will be filled with the existing values from the old table.
  • Syntax:
                  
      CREATE TABLE new_table_name AS
        SELECT column1, column2,...
        FROM existing_table_name
        WHERE ....;
                  
                
  • Example:
                  
      CREATE TABLE TestTable AS
        SELECT customername, contactname
        FROM customers;
                  
                
    This SQL creates a new table called "TestTables" (which is a copy of the "Customers" table).

Drop an existing table

  • The DROP TABLE statement is used to drop an existing table in a database.
  • Syntax:
    DROP TABLE table_name;
  • The TRUNCATE TABLE statement is used to delete the data inside a table, but not the table itself.
  • Syntax:
    TRUNCATE TABLE table_name;

Add, delete, or modify columns

  • The ALTER TABLE statement is used to add, delete, or modify columns in an existing table.
  • Syntax Example
    add a column in a table
                          
      ALTER TABLE table_name
      ADD column_name datatype;
                          
                        
                          
      ALTER TABLE Customers
      ADD Email varchar(255);
                          
                        
    delete a column in a table
                          
      ALTER TABLE table_name
      DROP COLUMN column_name;
                          
                        
                          
      ALTER TABLE Customers
      DROP COLUMN Email;
                          
                        
    change the data type of a column in a table
                          
      ALTER TABLE table_name
      MODIFY COLUMN column_name datatype;
                          
                        
                          
      ALTER TABLE Persons
      MODIFY COLUMN DateOfBirth year;
                          
                        

MySQL Constraints

  • SQL constraints are used to specify rules for data in a table.
  • Constraints can be specified when the table is created with the CREATE TABLE statement, or after the table is created with the ALTER TABLE statement.
  • Syntax:
                  
      CREATE TABLE table_name (
        column1 datatype constraint,
        column2 datatype constraint,
        column3 datatype constraint,
        ....
      );
                  
                
  • Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the table. If there is any violation between the constraint and the data action, the action is aborted.
  • The following constraints are commonly used in SQL:
    • NOT NULL - Ensures that a column cannot have a NULL value
    • UNIQUE - Ensures that all values in a column are different
    • PRIMARY KEY - A combination of a NOT NULL and UNIQUE. Uniquely identifies each row in a table
    • FOREIGN KEY - Prevents actions that would destroy links between tables
    • CHECK - Ensures that the values in a column satisfies a specific condition
    • DEFAULT - Sets a default value for a column if no value is specified
    • CREATE INDEX - Used to create and retrieve data from the database very quickly

MySQL NOT NULL Constraint

  • The NOT NULL constraint enforces a column to NOT accept NULL values.
  • This enforces a field to always contain a value, which means that you cannot insert a new record, or update a record without adding a value to this field.
  • Example:
                  
      CREATE TABLE Persons (
        ID int NOT NULL,
        LastName varchar(255) NOT NULL,
        FirstName varchar(255) NOT NULL,
        Age int
      );
                  
                

MySQL UNIQUE Constraint

  • The UNIQUE constraint ensures that all values in a column are different.
  • Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns.
  • A PRIMARY KEY constraint automatically has a UNIQUE constraint.
  • However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.
  • Example:
                  
      CREATE TABLE Persons (
        ID int NOT NULL,
        LastName varchar(255) NOT NULL,
        FirstName varchar(255),
        Age int,
        UNIQUE (ID)
      );
                  
                
  • To drop a UNIQUE constraint, use the following SQL:
                  
      ALTER TABLE Persons
      DROP INDEX UC_Person;
                  
                

MySQL PRIMARY KEY Constraint

  • The PRIMARY KEY constraint uniquely identifies each record in a table.
  • Primary keys must contain UNIQUE values, and cannot contain NULL values.
  • A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).
  • The following SQL creates a PRIMARY KEY on the "ID" column when the "Persons" table is created:
                  
      CREATE TABLE Persons (
        ID int NOT NULL,
        LastName varchar(255) NOT NULL,
        FirstName varchar(255),
        Age int,
        PRIMARY KEY (ID)
      );
                  
                
  • To allow naming of a PRIMARY KEY constraint, and for defining a PRIMARY KEY constraint on multiple columns, use the following SQL syntax:
                  
      CREATE TABLE Persons (
        ID int NOT NULL,
        LastName varchar(255) NOT NULL,
        FirstName varchar(255),
        Age int,
        CONSTRAINT PK_Person PRIMARY KEY (ID,LastName)
      );
                  
                
    In the example above there is only ONE PRIMARY KEY (PK_Person). However, the VALUE of the primary key is made up of TWO COLUMNS (ID + LastName).
  • To drop a PRIMARY KEY constraint, use the following SQL:
                  
      ALTER TABLE Persons
      DROP PRIMARY KEY;
                  
                

MySQL FOREIGN KEY Constraint

  • The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.
  • A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table.
  • The table with the foreign key is called the child table, and the table with the primary key is called the referenced or parent table.
  • The following SQL creates a FOREIGN KEY on the "PersonID" column when the "Orders" table is created:
                  
      CREATE TABLE Orders (
        OrderID int NOT NULL,
        OrderNumber int NOT NULL,
        PersonID int,
        PRIMARY KEY (OrderID),
        FOREIGN KEY (PersonID) REFERENCES Persons(PersonID)
      );
                  
                
  • To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:
                  
      CREATE TABLE Orders (
        OrderID int NOT NULL,
        OrderNumber int NOT NULL,
        PersonID int,
        PRIMARY KEY (OrderID),
        CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)
        REFERENCES Persons(PersonID)
      );
                  
                
  • Foreign key options [Restrict, Cascade, Set Null, No Action]
    When an UPDATE or DELETE operation affects a key value in the parent table that has matching rows in the child table, the result depends on the referential action specified using ON UPDATE and ON DELETE subclauses of the FOREIGN KEY clause. MySQL supports five options regarding the action to be taken, listed here:
    • Restrict : Nothing gonna be delete if there is a child row
    • Cascade : the child row will be delete / update too
    • Set Null : the child column will be set to null if you delete the parent
    • No action : The child row will not be concern of the delete / update
    Example:
                  
      CREATE TABLE parent (
        id INT NOT NULL,
        PRIMARY KEY (id)
      );
      CREATE TABLE child (
        id INT,
        parent_id INT,
        INDEX par_ind (parent_id),
        FOREIGN KEY (parent_id)
            REFERENCES parent(id)
            ON DELETE CASCADE
      );
                  
                
  • To drop a FOREIGN KEY constraint, use the following SQL:
                  
      ALTER TABLE Orders
      DROP FOREIGN KEY FK_PersonOrder;
                  
                

MySQL CHECK Constraint

  • The CHECK constraint is used to limit the value range that can be placed in a column.
  • If you define a CHECK constraint on a column it will allow only certain values for this column.
  • The following SQL creates a CHECK constraint on the "Age" column when the "Persons" table is created. The CHECK constraint ensures that the age of a person must be 18, or older:
                  
      CREATE TABLE Persons (
        ID int NOT NULL,
        LastName varchar(255) NOT NULL,
        FirstName varchar(255),
        Age int,
        CHECK (Age>=18)
      );
                  
                
  • To allow naming of a CHECK constraint, and for defining a CHECK constraint on multiple columns, use the following SQL syntax:
                  
      CREATE TABLE Persons (
        ID int NOT NULL,
        LastName varchar(255) NOT NULL,
        FirstName varchar(255),
        Age int,
        City varchar(255),
        CONSTRAINT CHK_Person CHECK (Age>=18 AND City='Sandnes')
      );
                  
                
  • To drop a CHECK constraint, use the following SQL:
                  
      ALTER TABLE Persons
      DROP CHECK CHK_PersonAge;
                  
                

MySQL DEFAULT Constraint

  • The DEFAULT constraint is used to set a default value for a column.
  • The default value will be added to all new records, if no other value is specified.
  • The following SQL sets a DEFAULT value for the "City" column when the "Persons" table is created:
                  
      CREATE TABLE Persons (
        ID int NOT NULL,
        LastName varchar(255) NOT NULL,
        FirstName varchar(255),
        Age int,
        City varchar(255) DEFAULT 'Sandnes'
      );
                  
                
  • The DEFAULT constraint can also be used to insert system values, by using functions like CURRENT_DATE():
                  
      CREATE TABLE Orders (
        ID int NOT NULL,
        OrderNumber int NOT NULL,
        OrderDate date DEFAULT CURRENT_DATE()
      );
                  
                
  • To drop a DEFAULT constraint, use the following SQL:
                  
      ALTER TABLE Persons
      ALTER City DROP DEFAULT;
                  
                

MySQL AUTO INCREMENT Field

  • Auto-increment allows a unique number to be generated automatically when a new record is inserted into a table.
  • Often this is the primary key field that we would like to be created automatically every time a new record is inserted.
  • By default, the starting value for AUTO_INCREMENT is 1, and it will increment by 1 for each new record.
  • The following SQL statement defines the "Personid" column to be an auto-increment primary key field in the "Persons" table:
                  
      CREATE TABLE Persons (
        Personid int NOT NULL AUTO_INCREMENT,
        LastName varchar(255) NOT NULL,
        FirstName varchar(255),
        Age int,
        PRIMARY KEY (Personid)
      );
                  
                
  • To let the AUTO_INCREMENT sequence start with another value, use the following SQL statement:
    ALTER TABLE Persons AUTO_INCREMENT=100;

MySQL Data Types

  • Each column in a database table is required to have a name and a data type.
  • An SQL developer must decide what type of data that will be stored inside each column when creating a table. The data type is a guideline for SQL to understand what type of data is expected inside of each column, and it also identifies how SQL will interact with the stored data.
  • In MySQL there are three main data types: string, numeric, and date and time.
  • String Data Types
    Data type Description
    CHAR(size) A FIXED length string (can contain letters, numbers, and special characters). The size parameter specifies the column length in characters - can be from 0 to 255. Default is 1
    VARCHAR(size) A VARIABLE length string (can contain letters, numbers, and special characters). The size parameter specifies the maximum column length in characters - can be from 0 to 65535
    BINARY(size) Equal to CHAR(), but stores binary byte strings. The size parameter specifies the column length in bytes. Default is 1
    VARBINARY(size) Equal to VARCHAR(), but stores binary byte strings. The size parameter specifies the maximum column length in bytes.
    TINYBLOB For BLOBs (Binary Large OBjects). Max length: 255 bytes
    TINYTEXT Holds a string with a maximum length of 255 characters
    TEXT(size) Holds a string with a maximum length of 65,535 bytes
    BLOB(size) For BLOBs (Binary Large OBjects). Holds up to 65,535 bytes of data
    MEDIUMTEXT Holds a string with a maximum length of 16,777,215 characters
    MEDIUMBLOB For BLOBs (Binary Large OBjects). Holds up to 16,777,215 bytes of data
    LONGTEXT Holds a string with a maximum length of 4,294,967,295 characters
    LONGBLOB For BLOBs (Binary Large OBjects). Holds up to 4,294,967,295 bytes of data
    ENUM(val1, val2, val3, ...) A string object that can have only one value, chosen from a list of possible values. You can list up to 65535 values in an ENUM list. If a value is inserted that is not in the list, a blank value will be inserted. The values are sorted in the order you enter them
    SET(val1, val2, val3, ...) A string object that can have 0 or more values, chosen from a list of possible values. You can list up to 64 values in a SET list
  • Numeric Data Types
    Data type Description
    BIT(size) A bit-value type. The number of bits per value is specified in size. The size parameter can hold a value from 1 to 64. The default value for size is 1.
    TINYINT(size) A very small integer. Signed range is from -128 to 127. Unsigned range is from 0 to 255. The size parameter specifies the maximum display width (which is 255)
    BOOL Zero is considered as false, nonzero values are considered as true.
    BOOLEAN Equal to BOOL
    SMALLINT(size) A small integer. Signed range is from -32768 to 32767. Unsigned range is from 0 to 65535. The size parameter specifies the maximum display width (which is 255)
    MEDIUMINT(size) A medium integer. Signed range is from -8388608 to 8388607. Unsigned range is from 0 to 16777215. The size parameter specifies the maximum display width (which is 255)
    INT(size) A medium integer. Signed range is from -2147483648 to 2147483647. Unsigned range is from 0 to 4294967295. The size parameter specifies the maximum display width (which is 255)
    INTEGER(size) Equal to INT(size)
    BIGINT(size) A large integer. Signed range is from -9223372036854775808 to 9223372036854775807. Unsigned range is from 0 to 18446744073709551615. The size parameter specifies the maximum display width (which is 255)
    FLOAT(size, d) A floating point number. The total number of digits is specified in size. The number of digits after the decimal point is specified in the d parameter. This syntax is deprecated in MySQL 8.0.17, and it will be removed in future MySQL versions
    FLOAT(p) A floating point number. MySQL uses the p value to determine whether to use FLOAT or DOUBLE for the resulting data type. If p is from 0 to 24, the data type becomes FLOAT(). If p is from 25 to 53, the data type becomes DOUBLE()
    DOUBLE(size, d) A normal-size floating point number. The total number of digits is specified in size. The number of digits after the decimal point is specified in the d parameter
    DOUBLE PRECISION(size, d)  
    DECIMAL(size, d) An exact fixed-point number. The total number of digits is specified in size. The number of digits after the decimal point is specified in the d parameter. The maximum number for size is 65. The maximum number for d is 30. The default value for size is 10. The default value for d is 0.
    DEC(size, d) Equal to DECIMAL(size,d)
    All the numeric data types may have an extra option: UNSIGNED or ZEROFILL. If you add the UNSIGNED option, MySQL disallows negative values for the column. If you add the ZEROFILL option, MySQL automatically also adds the UNSIGNED attribute to the column.
  • Date and Time Data Types
    Data type Description
    DATE A date. Format: YYYY-MM-DD. The supported range is from '1000-01-01' to '9999-12-31'
    DATETIME(fsp) A date and time combination. Format: YYYY-MM-DD hh:mm:ss. The supported range is from '1000-01-01 00:00:00' to '9999-12-31 23:59:59'. Adding DEFAULT and ON UPDATE in the column definition to get automatic initialization and updating to the current date and time
    TIMESTAMP(fsp) A timestamp. TIMESTAMP values are stored as the number of seconds since the Unix epoch ('1970-01-01 00:00:00' UTC). Format: YYYY-MM-DD hh:mm:ss. The supported range is from '1970-01-01 00:00:01' UTC to '2038-01-09 03:14:07' UTC. Automatic initialization and updating to the current date and time can be specified using DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP in the column definition
    TIME(fsp) A time. Format: hh:mm:ss. The supported range is from '-838:59:59' to '838:59:59'
    YEAR A year in four-digit format. Values allowed in four-digit format: 1901 to 2155, and 0000.
    MySQL 8.0 does not support year in two-digit format.

MySQL SELECT Statement

  • The SELECT statement is used to select data from a database.
  • The data returned is stored in a result table, called the result-set.
  • Syntax:
                  
      SELECT column1, column2, ...
      FROM table_name;
                  
                
  • If you want to select all the fields available in the table, use the following syntax:
    SELECT * FROM table_name;
  • The following SQL statement selects the "CustomerName", "City", and "Country" columns from the "Customers" table:
    SELECT CustomerName, City, Country FROM Customers;

MySQL WHERE Clause

  • The WHERE clause is used to filter records.
  • It is used to extract only those records that fulfill a specified condition.
  • Syntax:
                  
      SELECT column1, column2, ...
      FROM table_name
      WHERE condition;
                  
                
  • Example:
                  
      SELECT * FROM Customers
      WHERE Country = 'Mexico';
                  
                
  • Operators in The WHERE Clause
    Operator Description
    = Equal
    > Greater than
    < Less than
    >= Greater than or equal
    <= Less than or equal
    <> Not equal. Note: In some versions of SQL this operator may be written as !=
    BETWEEN Between a certain range
    LIKE Search for a pattern
    IN To specify multiple possible values for a column

MySQL Aliases

  • Aliases are used to give a table, or a column in a table, a temporary name.
  • Aliases are often used to make column names more readable.
  • An alias only exists for the duration of that query.
  • An alias is created with the AS keyword.
  • Syntax:
                  
      SELECT column_name AS alias_name
      FROM table_name;
                  
                
  • Examble:
                  
      SELECT CustomerID AS ID, CustomerName AS Customer
      FROM Customers;
                  
                
  • Single or double quotation marks are required if the alias name contains spaces:
                  
      SELECT CustomerName AS Customer, ContactName AS "Contact Person"
      FROM Customers;
                  
                
  • The following SQL statement creates an alias named "Address" that combine four columns (Address, PostalCode, City and Country):
                  
      SELECT CustomerName, CONCAT_WS(', ', Address, PostalCode, City, Country) AS Address
      FROM Customers;
                  
                

AND, OR and NOT Operators

  • The WHERE clause can be combined with AND, OR, and NOT operators.
  • The AND and OR operators are used to filter records based on more than one condition:
    • The AND operator displays a record if all the conditions separated by AND are TRUE.
    • The OR operator displays a record if any of the conditions separated by OR is TRUE.
  • The NOT operator displays a record if the condition(s) is NOT TRUE.
  • AND Syntax
                  
      SELECT column1, column2, ...
      FROM table_name
      WHERE condition1 AND condition2 AND condition3 ...;
                  
                
  • OR Syntax
                  
      SELECT column1, column2, ...
      FROM table_name
      WHERE condition1 OR condition2 OR condition3 ...;
                  
                
  • NOT Syntax
                  
      SELECT column1, column2, ...
      FROM table_name
      WHERE NOT condition;
                  
                
  • Example1:
                  
      SELECT * FROM Customers
      WHERE Country = 'Germany' AND (City = 'Berlin' OR City = 'Stuttgart');
                  
                
  • Example2:
                  
      SELECT * FROM Customers
      WHERE NOT Country = 'Germany' AND NOT Country = 'USA';
                  
                

ORDER BY Keyword

  • The ORDER BY keyword is used to sort the result-set in ascending or descending order.
  • The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
  • Syntax:
                  
      SELECT column1, column2, ...
      FROM table_name
      ORDER BY column1, column2, ... ASC|DESC;
                  
                
  • Example1:
                  
      SELECT * FROM Customers
      ORDER BY Country DESC;
                  
                
  • Example2:
                  
      SELECT * FROM Customers
      ORDER BY Country ASC, CustomerName DESC;
                  
                

MySQL EXISTS Operator

  • The EXISTS operator is used to test for the existence of any record in a subquery.
  • The EXISTS operator returns TRUE if the subquery returns one or more records.
  • Syntax:
                  
      SELECT column_name(s)
      FROM table_name
      WHERE EXISTS
      (SELECT column_name FROM table_name WHERE condition);
                  
                
  • Examples:
    The following SQL statement returns TRUE and lists the suppliers with a product price less than 20:
                  
      SELECT SupplierName
      FROM Suppliers
      WHERE EXISTS (SELECT ProductName FROM Products WHERE Products.SupplierID = Suppliers.supplierID AND Price < 20);
                  
                

NULL Values

  • A field with a NULL value is a field with no value.
  • If a field in a table is optional, it is possible to insert a new record or update a record without adding a value to this field. Then, the field will be saved with a NULL value.
  • A NULL value is different from a zero value or a field that contains spaces. A field with a NULL value is one that has been left blank during record creation!
  • It is not possible to test for NULL values with comparison operators, such as =, <, or <>.
    We will have to use the IS NULL and IS NOT NULL operators instead.
  • IS NULL Syntax :
                  
      SELECT column_names
      FROM table_name
      WHERE column_name IS NULL;
                  
                
  • IS NOT NULL Syntax :
                  
      SELECT column_names
      FROM table_name
      WHERE column_name IS NOT NULL;
                  
                

MySQL INSERT INTO Statement

  • The INSERT INTO statement is used to insert new records in a table.
  • It is possible to write the INSERT INTO statement in two ways:
    1. Specify both the column names and the values to be inserted:
                        
        INSERT INTO table_name (column1, column2, column3, ...)
        VALUES (value1, value2, value3, ...);
                        
                      
    2. If you are adding values for all the columns of the table, you do not need to specify the column names in the SQL query. However, make sure the order of the values is in the same order as the columns in the table. Here, the INSERT INTO syntax would be as follows:
                        
        INSERT INTO table_name
        VALUES (value1, value2, value3, ...);
                        
                      
  • Example:
                  
      INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
      VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');
                  
                

UPDATE Statement

  • The UPDATE statement is used to modify the existing records in a table.
  • Syntax:
                  
      UPDATE table_name
      SET column1 = value1, column2 = value2, ...
      WHERE condition;
                  
                
  • Be careful when updating records in a table! Notice the WHERE clause in the UPDATE statement. The WHERE clause specifies which record(s) that should be updated. If you omit the WHERE clause, all records in the table will be updated!
  • Example:
                  
      UPDATE Customers
      SET ContactName = 'Alfred Schmidt', City = 'Frankfurt'
      WHERE CustomerID = 1;
                  
                
  • Be careful when updating records. If you omit the WHERE clause, ALL records will be updated!

DELETE Statement

  • The DELETE statement is used to delete existing records in a table.
  • Syntax:
    DELETE FROM table_name WHERE condition;
  • Be careful when deleting records in a table! Notice the WHERE clause in the DELETE statement. The WHERE clause specifies which record(s) should be deleted. If you omit the WHERE clause, all records in the table will be deleted!
  • Example:
    DELETE FROM Customers WHERE CustomerName='Alfreds Futterkiste';
  • Delete All Records
    It is possible to delete all rows in a table without deleting the table. This means that the table structure, attributes, and indexes will be intact:
    DELETE FROM table_name;