Author: alien

  • Khóa học miễn phí SQL – Rename Table nhận dự án làm có lương

    SQL – Rename Table

    Table of content


    SQL provides two ways to rename an MySQL table. You can use either SQL RENAME TABLE or ALTER TABLE statement to change a table name in MySQL RDBMS.

    The SQL RENAME TABLE Statement

    You can change a MySQL table name using SQL RENAME TABLE statement.

    Syntax

    Following is the syntax of the SQL RENAME TABLE Statement −

    RENAME TABLE table_name TO new_table_name;
    

    Where, table_name is the current name of an existing table and new_table_name is the new name of the table.

    Example: SQL RENAME TABLE Statement

    Let us with the name CUSTOMERS which contains the personal details of customers including their name, age, address and salary etc. as shown below −

    CREATE TABLE CUSTOMERS (
       ID INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    

    Now, let us insert few records into this table using the INSERT statement as follows −

    INSERT INTO CUSTOMERS VALUES
    (1, ''Ramesh'', 32, ''Ahmedabad'', 2000.00 ),
    (2, ''Khilan'', 25, ''Delhi'', 1500.00 ),
    (3, ''Kaushik'', 23, ''Kota'', 2000.00 ),
    (4, ''Chaitali'', 25, ''Mumbai'', 6500.00 ),
    (5, ''Hardik'', 27, ''Bhopal'', 8500.00 ),
    (6, ''Komal'', 22, ''Hyderabad'', 4500.00 ),
    (7, ''Muffy'', 24, ''Indore'', 10000.00 );
    

    The table will be created as follows −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.00
    3 Kaushik 23 Kota 2000.00
    4 Chaitali 25 Mumbai 6500.00
    5 Hardik 27 Bhopal 8500.00
    6 Komal 22 Hyderabad 4500.00
    7 Muffy 24 Indore 10000.00

    Following SQL Query changes the name of the CUSTOMERS table to BUYERS

    RENAME TABLE CUSTOMERS to BUYERS;
    

    Verification

    Once you change the name of a table, you can start using the new table name in your SQL queries.

    SELECT * FROM BUYERS;
    

    If table name got changed successfully, then it should list down all the records which were available in CUSTOMERS table.

    The SQL ALTER TABLE Statement

    The ALTER TABLE statement can be used to change or modify the structure of an existing table i.e. using this statement you can add/delete columns, create/destroy indexes, change the of the existing columns, rename the columns and, we can even rename the table.

    Syntax

    Following is the syntax of the SQL ALTER TABLE statement to rename an existing table −

    ALTER TABLE table_name RENAME [TO|AS] new_table_name
    

    Example: SQL ALTER TABLE Statement

    Following SQL ALTER TABLE statement will change the table name from BUYERS to CUSTOMERS.

    ALTER TABLE BUYERS RENAME TO CUSTOMERS;
    

    Verification

    Once you change the name of the table to CUSTOMERS, you can start using this name in your SQL queries.

    SELECT * FROM CUSTOMERS;
    

    This will produce the following result:

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.00
    3 Kaushik 23 Kota 2000.00
    4 Chaitali 25 Mumbai 6500.00
    5 Hardik 27 Bhopal 8500.00
    6 Komal 22 Hyderabad 4500.00
    7 Muffy 24 Indore 10000.00

    Renaming a Table in SQL Server

    There isn”t a query in SQL Server that can rename a table directly. However, it does give you access to a stored procedure called sp_rename that enables you to rename a table.

    The sp_rename is a system stored procedure (set of pre-built subroutines that perform tasks within the database) in SQL that can be used to rename various database objects including tables, columns, indexes, and constraints.

    Syntax

    Following is the basic syntax to rename a table in SQL Server −

    EXEC sp_rename ''old_table_name'', ''new_table_name''
    

    Here, you must ensure that old table name is present in the database and that new table name does not already exist. Otherwise, it will issue a warning. Second important point is to make sure that the table is not locked and there is no active transaction involving this table.

    Example: Renaming a Table in SQL Server

    Assume we already have the CUSTOMERS table in our database. Now, we are going to rename this table from CUSTOMERS to WORKERS, using the following query −

    EXEC sp_rename ''CUSTOMERS'', ''WORKERS
    

    Output

    The result obtained is as shown below −

    Completion time: 2023-08-15T19:21:49.1144163+05:30
    

    Verification

    We can verify whether the changes are reflected by retrieving its contents using the SELECT statement as follows −

    SELECT * FROM WORKERS;
    

    This will list down all the records available in WORKERS table as follows −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.00
    3 Kaushik 23 Kota 2000.00
    4 Chaitali 25 Mumbai 6500.00
    5 Hardik 27 Bhopal 8500.00
    6 Komal 22 Hyderabad 4500.00
    7 Muffy 24 Indore 10000.00

    Because you have renamed the table to WORKERS so if you try to get the details by using the old table name, it will throw an error showing that the table does not exist.

    Rules to be followed while renaming tables

    When renaming tables in SQL, there are some rules and best practices that should be followed to ensure that the renaming process goes smoothly and does not cause any unintended consequences or issues.

    • Avoid renaming system tables − System tables are tables that are created and used by the database management system itself. Renaming these tables can cause issues with the functioning of the database system, so it is generally not recommended to rename system tables.

    • Update all references to the table − After renaming a table, any , , triggers, or other database objects that reference the table will need to be updated to use the new name of the table. Failure to update these references can result in errors or issues with the functioning of the database system.

    • Test thoroughly − Before renaming a table in a production environment, it is important to test the renaming process thoroughly in a development or testing environment to ensure that all references to the table have been updated correctly and that the database system continues to function as expected.

    • Use a consistent naming convention − It is a good practice to use a consistent naming convention for tables and other database objects to make it easier to understand and maintain the database system. If you need to rename a table, consider following the same naming convention that you have used for other tables in the database.

    • Backup the database − Before renaming a table, it is recommended to create a to ensure that you have a restore point; in case anything goes wrong during the renaming process.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Clone Tables nhận dự án làm có lương

    SQL – Clone Tables

    Table of content


    There may be a situation when you need an exact copy of a table with the same columns, attributes, indexes, default values and so forth. Instead of spending time on creating the exact same version of an existing table, you can create a clone of the existing table.

    SQL Cloning Operation allows to create the exact copy of an existing table along with its definition. There are three types of cloning possible using SQL in various RDBMS; they are listed below −

    • Simple Cloning
    • Shallow Cloning
    • Deep Cloning

    Simple Cloning in MySQL

    Simple cloning operation creates a new replica table from the existing table and copies all the records in newly created table. To break this process down, a new table is created using the CREATE TABLE statement; and the data from the existing table, as a result of SELECT statement, is copied into the new table.

    Here, clone table inherits only the basic column definitions like the NULL settings and default values from the original table. It does not inherit the indices and AUTO_INCREMENT definitions.

    Syntax

    Following is the basic syntax to perform simple cloning in MySQL−

    CREATE TABLE new_table SELECT * FROM original_table;
    

    Example

    Consider the following existing CUSTOMERS table which will be cloned in next new few steps.

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.00
    3 Kaushik 23 Kota 2000.00
    4 Chaitali 25 Mumbai 6500.00
    5 Hardik 27 Bhopal 8500.00
    6 Komal 22 Hyderabad 4500.00
    7 Muffy 24 Indore 10000.00

    Now let”s use the following SQL statement to create NEW_CUSTOMERS table using the existing table CUSTOMERS.

    CREATE TABLE NEW_CUSTOMERS SELECT * FROM CUSTOMERS;
    

    Output

    The output is displayed as −

    Query OK, 7 rows affected (0.06 sec)
    Records: 7  Duplicates: 0  Warnings: 0
    

    Verification

    To verify whether the table has been cloned successfully, we can use the following SELECT query −

    SELECT * FROM NEW_CUSTOMERS;
    

    If NEW_CUSTOMERS table is created successfully, then it should get all the records which are available in CUSTOMERS table.

    Shallow Cloning in MySQL

    Shallow cloning operation creates a new replica table from the existing table but does not copy any data records into newly created table, so only new but empty table is created.

    Here, the clone table contains only the structure of the original table along with the column attributes including indices and AUTO_INCREMENT definition..

    Syntax

    Following is the basic syntax to perform shallow cloning in MySQL RDBMS −

    CREATE TABLE new_table LIKE original_table;
    

    Example

    Following is an example to create a shallow clone copy of the existing table CUSTOMERS.

    CREATE TABLE SHALL_CUSTOMERS LIKE CUSTOMERS;
    

    Output

    The output is displayed as −

    Query OK, 0 rows affected (0.06 sec)
    

    Verification

    To verify whether the table has been cloned successfully, we can use the following DESC table_name query −

    DESC SHALL_CUSTOMERS;
    

    This will display the following information about the SHALL_CUSTOMERS table which is just a replica of CUSTOMERS table −

    Field Type Null Key Default Extra
    ID int(11) NO PRI NULL
    NAME varchar(20) NO NULL
    AGE int(11) NO NULL
    ADDRESS char(25) YES NULL
    SALARY decimal(18,2) YES NULL

    Deep Cloning in MySQL

    Deep cloning operation is a combination of simple cloning and shallow cloning. It not only copies the structure of the existing table but also its data into the newly created table. Hence, the new table will have all the contents from existing table and all the attributes including indices and the AUTO_INCREMENT definitions.

    Since it is a combination of shallow and simple cloning, this type of cloning will have two different queries to be executed: one with CREATE TABLE statement and one with INSERT INTO statement. The CREATE TABLE statement will create the new table by including all the attributes of existing table; and INSERT INTO statement will insert the data from existing table into new table.

    Syntax

    Following is the basic syntax to perform deep cloning in MySQL RDBMS −

    CREATE TABLE new_table LIKE original_table;
    INSERT INTO new_table SELECT * FROM original_table;
    

    Example

    Following is an example to create a deep clone copy of the existing table CUSTOMERS. First step is to create a shallow clone of the existing table.

    CREATE TABLE DEEP_CUSTOMERS LIKE CUSTOMERS;
    

    The output is displayed as −

    Query OK, 0 rows affected (0.06 sec)
    

    Now second step is to copy all the records from the CUSTOMERS table to DEEP_CUSTOMERS.

    INSERT INTO DEEP_CUSTOMERS SELECT * FROM CUSTOMERS;
    

    Output

    The output is displayed as −

    Query OK, 7 rows affected (0.01 sec)
    Records: 7  Duplicates: 0  Warnings: 0
    

    Verification

    To verify whether the table has been cloned successfully, we can use the following SELECT query −

    SELECT * FROM DEEP_CUSTOMERS;
    

    If DEEP_CUSTOMERS table is cloned successfully, then it should get all the records which are available in CUSTOMERS.

    Table Cloning in SQL Server

    However, there is no direct way to fully clone a table in an SQL server. However, we have some work around to handle the situation.

    SELECT…INTO STATEMENT

    MS SQL Server can make use of the SELECT…INTO statement to create a new table and copies the data from an existing table into it. However, this command only copies the data and not the definition of it, thus, omitting constraints, indexes etc., if any. They need to be added separately if one wishes to have the exact same structure of the original table in their new table.

    You can use the SELECT…INTO command to copy a table within the same database as well as across different databases.

    Syntax

    Following is the basic syntax of the SELECT…INTO statement −

    SELECT * INTO new_table FROM original_table;
    

    The above SQL command will create a table new_table using the structure of original_table and then it will copy all the data from original_table to new_table.

    Example

    Consider the following existing CUSTOMERS table which will be cloned in this section.

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.00
    3 Kaushik 23 Kota 2000.00
    4 Chaitali 25 Mumbai 6500.00
    5 Hardik 27 Bhopal 8500.00
    6 Komal 22 Hyderabad 4500.00
    7 Muffy 24 Indore 10000.00

    Now, if you want to clone the data of this table into a new table NEW_CUSTOMERS, let”s use the following SQL query as shown below −

    SELECT * INTO NEW_CUSTOMERS FROM CUSTOMERS;
    

    Output

    The output will be displayed as −

    (7 rows affected)
    

    Verification

    To verify whether all the data has been copied into the new table NEW_CUSTOMERS, we shall use the SQL SELECT statement as follows −

    SELECT * FROM NEW_CUSTOMERS;
    

    If NEW_CUSTOMERS table is created successfully, then it should get all the records which are available in CUSTOMERS table.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Truncate Table nhận dự án làm có lương

    SQL – TRUNCATE TABLE

    Table of content


    SQL provides command to TRUNCATE a table completely in one go instead of deleting table records one by one which will be very time consuming and cumbersome process.

    The SQL TRUNCATE TABLE Statement

    The SQL TRUNCATE TABLE command is used to empty a table. This command is a sequence of DROP TABLE and CREATE TABLE statements and requires the DROP privilege.

    You can also use DROP TABLE command to but it will remove the complete table structure from the database and you would need to re-create this table once again if you wish you store some data again.

    Syntax

    The basic syntax of a TRUNCATE TABLE command is as follows.

    TRUNCATE TABLE table_name;
    

    Example

    First let”s create a table CUSTOMERS which can store the personal details of customers including their name, age, address and salary etc. as shown below −

    CREATE TABLE CUSTOMERS (
       ID INT NOT NULL,
       NAME VARCHAR (20) NOT NULL,
       AGE INT NOT NULL,
       ADDRESS CHAR (25),
       SALARY DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    

    Now insert values into this table using the INSERT statement as follows −

    INSERT INTO CUSTOMERS VALUES
    (1, ''Ramesh'', 32, ''Ahmedabad'', 2000.00 ),
    (2, ''Khilan'', 25, ''Delhi'', 1500.00 ),
    (3, ''Kaushik'', 23, ''Kota'', 2000.00 ),
    (4, ''Chaitali'', 25, ''Mumbai'', 6500.00 ),
    (5, ''Hardik'', 27, ''Bhopal'', 8500.00 ),
    (6, ''Komal'', 22, ''Hyderabad'', 4500.00 ),
    (7, ''Muffy'', 24, ''Indore'', 10000.00 );
    

    The table will be created as follows −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.00
    3 Kaushik 23 Kota 2000.00
    4 Chaitali 25 Mumbai 6500.00
    5 Hardik 27 Bhopal 8500.00
    6 Komal 22 Hyderabad 4500.00
    7 Muffy 24 Indore 10000.00

    Following SQL TRUNCATE TABLE CUSTOMER statement will remove all the records of the CUSTOMERS table −

    TRUNCATE TABLE CUSTOMERS;
    

    Verification

    Now, the CUSTOMERS table is truncated and the output from SELECT statement will be as shown in the code block below −

    SELECT * FROM CUSTOMERS;
    

    Following will be the output −

    Empty set (0.00 sec)
    

    TRUNCATE vs DELETE

    Even though the TRUNCATE and DELETE commands work similar logically, there are some major differences that exist between them. They are detailed in the table below.

    DELETE TRUNCATE

    The in SQL removes one or more rows from a table based on the conditions specified in a WHERE Clause.

    SQL”s TRUNCATE command is used to remove all of the rows from a table, regardless of whether or not any conditions are met.

    It is a DML(Data Manipulation Language) command.

    It is a DDL(Data Definition Language) command.

    There is a need to make a manual COMMIT after making changes to the DELETE command, for the modifications to be committed.

    When you use the TRUNCATE command, the modifications made to the table are committed automatically.

    It deletes rows one at a time and applies same criteria to each deletion.

    It removes all of the information in one go.

    The WHERE clause serves as the condition in this case.

    The WHERE Clause is not available.

    All rows are locked after deletion.

    TRUNCATE utilizes a table lock, which locks the pages so they cannot be deleted.

    It makes a record of each and every transaction in the log file.

    The only activity recorded is the deallocation of the pages on which the data is stored.

    It consumes a greater amount of transaction space compared to TRUNCATE command.

    It takes comparatively less amount of transaction space.

    If there is an identity column, the table identity is not reset to the value it had when the table was created.

    It returns the table identity to a value it was given as a seed.

    It requires authorization to delete.

    It requires table alter permission.

    When it comes to large databases, it is much slower.

    It is much faster.

    TRUNCATE vs DROP

    Unlike TRUNCATE that resets the table structure, completely frees the table space from the memory. They are both Data Definition Language (DDL) operations as they interact with the definitions of database objects; which allows the database to automatically commit once these commands are executed with no chance to roll back.

    However, there are still some differences exist between these two commands, which have been summarized in the following table −

    DROP TRUNCATE

    The DROP command in SQL removes an entire table from a database including its definition, indexes, constraints, data etc.

    The TRUNCATE command is used to remove all of the rows from a table, regardless of whether or not any conditions are met and resets the table definition.

    It is a DDL(Data Definition Language) command.

    It is also a DDL(Data Definition Language) command.

    The table space is completely freed from the memory.

    The table still exists in the memory.

    All the integrity constraints are removed.

    The integrity constraints still exist in the table.

    Requires ALTER and CONTROL permissions on the table schema and table respectively, to be able to perform this command.

    Only requires the ALTER permissions to truncate the table.

    DROP command is much slower than TRUNCATE but faster than DELETE.

    TRUNCATE command is faster than both DROP and DELETE commands.


    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Rename Database nhận dự án làm có lương

    SQL – Rename Database

    Table of content


    There can be several reasons to rename a database name. One of the reasons could be to avoid naming conflicts or to separate different types of data into different databases. Another reason can be to arrange them in an organized way which makes them more descriptive and easier to manage.

    The ALTER DATABASE…MODIFY Statement

    The ALTER DATABASE…MODIFY statement in SQL is used to rename the name of an existing database name in SQL Database Server. Please note that this command does not work in MySQL database.

    Syntax

    Following is the syntax of the ALTER DATABASE…MODIFY command −

    ALTER DATABASE OldDatabaseName MODIFY NAME = NewDatabaseName;
    

    Example

    Following is the SQL command in SQL Server to rename the database testDB to tutorialsDB:

    ALTER DATABASE testDB MODIFY NAME = tutorialsDB ;
    

    Rename Database using Dump and Reimport

    If you are willing to rename a database name in , then simple way is to dump the complete database in an SQL file and then re-import it into a new database. This is three step process which we will follow in this tutorial:

    Step 1 – Dump Old Database

    Consider you want to rename testDB database to tutorialsDB. So first we will dump it in a simple SQL file using MySQL mysqldump command. This operation will be performed from command line and will require a database user name and password, preferably admin privilege.

    $ mysqldump -u username -p"password" -R testDB > testDB.sql
    

    We are using the -p flag immediately followed by our password to connect to the database with no space between. The -R is required to tell mysqldump to copy stored procedures and functions along with the normal data from the database.

    Step 2 – Create New Database

    Next step is to using mysqladmin prompt command as follows:

    $ mysqladmin -u username -p"password" create tutorialsDB;
    

    Step 3 – Import Old Database

    The final step is to import old database into new database as follwing:

    $ mysql -u username -p"password" tutorialsDB < testDB.sql;
    

    Step 4 – Verification (Optional)

    Now you can verify the changes by listing down all the available databases:

    SHOW DATABASES;
    

    Output

    The output will be displayed as −

    Database
    performance_schema
    information_schema
    mysql
    testDB
    tutorialsDB

    Step 5 – Verification (Optional)

    Once you are satisfied with your changes, you can delete your old database as follows:

    DROP DATABASE testDB;
    

    Rename Database in SQL using RENAME DATABASE…TO (obsoleted)

    SQL provides a simple RENAME DATABASE…TO statement to rename an existing database. If you want to rename a database, make sure there is no active transaction in progress otherwise the complete operation might halt once you rename the database.

    Note: The RENAME DATABASE…TO is obsoleted.

    Syntax

    Following is the syntax of the RENAME DATABASE…TO statement −

    RENAME DATABASE OldDatabaseName TO NewDatabaseName;
    

    Example

    Before renaming a database, let us list down all the available databases −

    SHOW DATABASES;
    

    The output will be displayed as −

    Database
    performance_schema
    information_schema
    mysql
    testDB

    Now, issue the following command to rename the database testDB to tutorialsDB:

    RENAME DATABASE testDB TO tutorialsDB;
    
    There used to be a simple RENAME DATABASE command in older versions of MySQL which was intended to rename database but RENAME DATABASE command has been removed from all newer versions to avoid security risks.

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Show Tables nhận dự án làm có lương

    SQL – Show Tables (Listing Tables)

    Table of content


    There are several instances when you need to retrieve a list of tables from your database. This could be done for testing purposes, to identify any existing tables before adding or removing any, or for any other reason. This tutorial will discuss how we can list down all the table in MySQL, SQL Server and Oracle using simple SQL commands.

    MySQL – Listing Tables

    You can use SQL SHOW TABLES statements in MySQL to list down all the tables available in a selected database.

    Syntax

    Following is the syntax to list all the tables in SQL in MySQL −

    SHOW TABLES;
    

    Example

    Following is an example which will list down all the tables from a testDB database.

    USE testDB;
    
    SHOW TABLES;
    

    This will display the following output depending on the number of tables available in your database.

    Tables_in_testDB
    CALENDAR
    CUSTOMERS
    COMPANIES
    SALARY

    SQL Server – Listing Tables

    SQL Server does not provide SHOW TABLE command in an SQL Server. Instead, we can use the “SELECT” statement to retrieve information about tables in a database. We have three different commands to use with the SELECT statement to list all the tables in a database −

    • sys.tables

    • information_schema.tables

    • sysobjects

    The SYS.TABLES View

    Following is the syntax to list down all the tables in SQL using the SYS.TABLES view −

    SELECT * FROM SYS.TABLES;
    

    Following is the output of the above query −

    name object_id principal_id schema_id
    CUSTOMER 4195065 NULL 1
    ORDERS 68195293 NULL 1
    COMPANIES 100195407 NULL 1
    SALARY 2107154552 NULL 1

    The INFORMATION_SCHEMA.TABLES View

    Following is the syntax to list down all the tables in SQL using the INFORMATION_SCHEMA.TABLES view −

    SELECT table_name, table_type FROM INFORMATION_SCHEMA.TABLES;
    

    Following is the output of the above query −

    table_name table_type
    CUSTOMER BASE TABLE
    ORDERS BASE TABLE
    COMPANIES BASE TABLE
    SALARY BASE TABLE

    The SYSOBJECTS View

    You can use SYSOBJECTS view to retrieve the information of all the objects created in SQL Server database, including stored procedures, views, system tables and user-defined tables. Following is the basic syntax of using sysobjects view −

    SELECT name, id, xtype FROM sysobjects WHERE xtype = ''U
    
    Value Meaning
    AF Aggregate function (CLR)
    C CHECK constraint
    D Default or DEFAULT constraint
    F FOREIGN KEY constraint
    L Log
    FN Scalar function
    FS Assembly (CLR) scalar-function
    FT Assembly (CLR) table-valued function
    IF In-lined table-function
    IT Internal table
    P Stored procedure
    PC Assembly (CLR) stored-procedure
    PK PRIMARY KEY constraint (type is K)
    RF Replication filter stored procedure
    S System table
    SN Synonym
    SQ Service queue
    TA Assembly (CLR) DML trigger
    TF Table function
    TR SQL DML Trigger
    TT Table type
    U User table
    UQ UNIQUE constraint (type is K)
    V View
    X Extended stored procedure

    This will produce following result −

    name id xtype
    CUSTOMER 4195065 U
    ORDERS 68195293 U
    COMPANIES 100195407 U
    SALARY 2107154552 U

    Oracle – Listing Tables

    There are following three SQL SELECT statements which you can use to list down the tables available in Oracle.

    Listing ALL Tables

    Following is the SQL SELECT statement which will list down all the available tables in an Oracle Database.

    SELECT owner, table_name FROM ALL_TABLES
    

    Listing DBA Tables

    Following is the SQL SELECT statement which will list down all the DBA related tables in an Oracle Database.

    SELECT owner, table_name FROM DBA_TABLES
    

    Listing USER Tables

    Following is the SQL SELECT statement which will list down all the USER created tables in an Oracle Database.

    SELECT owner, table_name FROM USER_TABLES
    

    Listing ALL Views

    Following is the SQL SELECT statement which will list down all the views available in an Oracle Database.

    SELECT view_name FROM ALL_VIEWS;
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Create Table nhận dự án làm có lương

    SQL – CREATE Table

    Table of content


    This tutorial will teach you how to use SQL to create tables in RDBMS. We use CREATE TABLE command to create a Table in a Database.

    In RDBMS, Database tables are used to store the data in the form of some structures (fields and records). Here, a field is a column defining the type of data to be stored in a table and record is a row containing actual data. In simple words, we can say a Table is a combination of rows and columns.

    provides various queries to interact with the data in a convenient way. We can use SQL statements to create and delete tables, inserting, updating and deleting data in these tables.

    For a more detail on different concepts related to RDBMS please check tutorial.

    The SQL CREATE TABLE Statement

    SQL provides the CREATE TABLE statement to create a new table in a given database. An SQL query to create a table must define the structure of a table. The structure consists of the name of a table and names of columns in the table with each column”s data type. Note that each table must be uniquely named in a database.

    Syntax

    CREATE TABLE statement is used to create a new table in a database. −

    CREATE TABLE table_name(
       column1 datatype,
       column2 datatype,
       column3 datatype,
       .....
       columnN datatype,
       PRIMARY KEY( one or more columns )
    );
    

    Here are the key points-

    • CREATE TABLE is the keyword telling the database system what you want to do. In this case, you want to create a new table. The unique name or identifier for the table follows the CREATE TABLE statement.
    • The column parameters (e.g. column1, column2, column3, etc.) specify the names of the columns of the table.
    • The datatype parameter specifies the type of data the column can hold (e.g. integer, varchar, string, etc.).
    • PRIMARY KEY constraint uniquely identifies each record in a table. Primary keys must contain UNIQUE values, and cannot contain NULL values.

    Example: Creating Table in SQL

    CREATE TABLE CUSTOMERS(
       ID          INT NOT NULL,
       NAME        VARCHAR (20) NOT NULL,
       AGE         INT NOT NULL,
       ADDRESS     CHAR (25),
       SALARY      DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    

    Here are the key points-

    • The following code block is an example, which creates a CUSTOMERS table with column name ID, NAME, AGE, ADDRESS and, SALARY and ID as a primary key.
    • NOT NULL are the constraints showing that these fields cannot be NULL while creating records in this table.

    Verification

    Once your table is created, you can check if it has been created successfully or not. You can use SQL DESC table_name command to list down the description of the table as follows:

    DESC CUSTOMERS;
    

    This will display the structure of the table created: column names, their respective data types, constraints (if any) etc.

    Field Type Null Key Default Extra
    ID int(11) NO PRI NULL
    NAME varchar(20) NO NULL
    AGE int(11) NO NULL
    ADDRESS char(25) YES NULL
    SALARY decimal(18,2) YES NULL

    Now, you have CUSTOMERS table available in your database which you can use to store the required information related to customers.

    SQL CREATE TABLE IF NOT EXISTS

    Consider a situation where you will try to create a table which already exists, in such situation will throw the following error.

    ERROR 1050 (42S01): Table ''CUSTOMERS'' already exists
    

    So to avoid such error we can use SQL command CREATE TABLE IF NOT EXISTS to create a table.

    Syntax

    Following is the basic syntax of a CREATE TABLE IF NOT EXISTS statement −

    CREATE TABLE IF NOT EXISTS table_name(
       column1 datatype,
       column2 datatype,
       column3 datatype,
       .....
       columnN datatype,
       PRIMARY KEY( one or more columns )
    );
    

    Example: Creating Table if Not Exists

    The following SQL command will create the CUSTOMERS table only when there is no table exists with the same name otherwise it will exit without any error.

    CREATE TABLE IF NOT EXISTS CUSTOMERS(
       ID          INT NOT NULL,
       NAME        VARCHAR (20) NOT NULL,
       AGE         INT NOT NULL,
       ADDRESS     CHAR (25),
       SALARY      DECIMAL (18, 2),
       PRIMARY KEY (ID)
    );
    

    Creating a Table from an Existing Table

    Instead of creating a new table every time, one can also copy an existing table and its contents including its structure, into a new table. This can be done using a combination of the CREATE TABLE statement and the SELECT statement. Since its structure is copied, the new table will have the same column definitions as the original table. Furthermore, the new table would be populated using the existing values from the old table.

    Syntax

    The basic syntax for creating a table from another table is as follows −

    CREATE TABLE NEW_TABLE_NAME AS
    SELECT [column1, column2...columnN]
    FROM EXISTING_TABLE_NAME
    WHERE Condition;
    

    Here, column1, column2… are the fields of the existing table and the same would be used to create fields of the new table.

    Example: Creating Table from an Existing Table

    Following is an example, which would create a table SALARY using the CUSTOMERS table and having the fields customer ID and customer SALARY −

    CREATE TABLE SALARY AS
    SELECT ID, SALARY
    FROM CUSTOMERS;
    

    This will create a new table SALARY which will have the following structure −

    Field Type Null Key Default Extra
    ID int(11) NO PRI NULL
    SALARY decimal(18,2) YES NULL

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Select Database nhận dự án làm có lương

    SQL – SELECT Database, USE Statement

    Table of content


    To work with a database in SQL, we need to first select the database we want to work with. After selecting the database, we can perform various operations on it such as creating tables, inserting data, updating data, and deleting data.

    The USE DATABASE Statement

    The SQL USE DATABASE statement is used to select a database from a list of databases available in the system. Once a database is selected, we can perform various operations on it such as , , updating data, and .

    Syntax

    Following is the syntax of the USE DATABASE statement in SQL −

    USE DatabaseName;
    

    Here, the DatabaseName is the name of the database that we want to select. The database name is always unique within the RDBMS.

    Example

    First of all we will create a database using the following SQL CREATE DATABASE query −

    CREATE DATABASE testDB;
    

    Now, we can list all the available databases as follws −

    SHOW DATABASES;
    

    The output will be displayed as −

    Database
    master
    performance_schema
    information_schema
    mysql
    testDB

    Example: Select/Switch Database

    Following query is used to select/switch the current database to testDB

    USE testDB;
    

    Output

    Database changed
    

    Once we finish switching to the database testDB we can perform operations such as creating a table, and inserting data in that table as shown below −.

    CREATE TABLE CALENDAR(MONTHS DATE NOT NULL);
    

    Now, let us insert some records in the CALENDAR table using SQL INSERT statements as shown in the query below −

    INSERT INTO CALENDAR(MONTHS) VALUES(''2023-01-01'');
    INSERT INTO CALENDAR(MONTHS) VALUES(''2023-02-01'');
    INSERT INTO CALENDAR(MONTHS) VALUES(''2023-03-01'');
    INSERT INTO CALENDAR(MONTHS) VALUES(''2023-04-01'');
    INSERT INTO CALENDAR(MONTHS) VALUES(''2023-12-01'');
    

    Let”s verify the operation by listing all the records from CALENDAR table using SQL SELECT statement as shown below −

    SELECT * FROM CALENDAR;
    

    Output

    The output will be displayed as −

    MONTHS
    2023-01-01
    2023-02-01
    2023-03-01
    2023-04-01
    2023-12-01

    Selecting a Non Existing Database

    An attempt to select a non-existent database will result in an error. In the following query we are trying to switch to the database which does not exist −

    Example

    USE unknownDatabase;
    

    Output

    On executing the above query, the output will be displayed as −

    ERROR 1049 (42000): Unknown database ''unknownDatabase''
    

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Show Databases nhận dự án làm có lương

    SQL – Show Databases

    Table of content


    Many a times you face a situation where you need to list down all the available databases. MySQL provides a convenient way to list down all the databases using SHOW DATABASES command where as there is no particular command in MS SQL Server to show or list the databases but, you can use the SELECT…FROM command as a work around list down available databases.

    List Databases using SQL

    The SQL SHOW DATABASES statement is used to list down all the available databases in MySQL database. You can use SHOW SCHEMAS as an alternate command for SHOW DATABASES.

    Syntax

    Following is the syntax of SQL SHOW DATABASES to list down all the available databases in MySQL −

    SHOW DATABASES [LIKE ''pattern'' | WHERE expr] ;
    

    We can use LIKE or WHERE clause along with SHOW DATABASES to filter out a list of databases.

    Example

    Following is an example to list down all the available databases.

    SHOW DATABASES;
    

    The output will be displayed as follows. This output depends on the number of databases available in the system −

    Database
    performance_schema
    information_schema
    mysql
    testDB

    Following is an example to list down all the databases whose name starts with test.

    SHOW DATABASES LIKE ''test%
    

    The output will be displayed as follows −

    Database (test%)
    testDB

    The SHOW SCHEMAS Statement

    You can use the SHOW SCHEMAS statement as an alternate for the SHOW DATABASES statement.

    Syntax

    Following is the syntax of the SQL SHOW SCHEMAS statement to list down all the available databases in MySQL −

    SHOW SCHEMAS [LIKE ''pattern'' | WHERE expr] ;
    

    We can use LIKE or WHERE clause along with SHOW SCHEMAS to filter out a list of databases.

    Example

    Following is an example to list down all the available databases.

    SHOW SCHEMAS;
    

    The output will be displayed as follows. This output depends on the number of databases available in the system −

    Database
    performance_schema
    information_schema
    mysql
    testDB

    Following is an example to list down all the databases whose name starts with test.

    SHOW SCHEMAS LIKE ''test%
    

    The output will be displayed as follows −

    Database (test%)
    testDB

    The SELECT…FROM Statement

    If you are working with MS SQL Server then you can use the SELECT…FROM statement to list down all the available databases as shown below.

    SQL> SELECT * FROM sys.databases;
    

    Output

    If we execute the above query, it returns a table that lists down all the databases and associated information about the databases.

    name database_id source_database_id owner_sid
    master 1 NULL 001
    tempdb 2 NULL 001
    model 3 NULL 001
    msdb 4 NULL 001
    testDB 5 NULL 001000

    The EXEC sp_databases Statement

    If you are using MS SQL Server then you can use the following EXEC sp_databases statement to list down all the databases −

    SQL> EXEC sp_databases;
    

    Output

    This will display the same result as we got from SELECT…FROM statement.

    name database_id source_database_id owner_sid
    master 1 NULL 001
    tempdb 2 NULL 001
    model 3 NULL 001
    msdb 4 NULL 001
    testDB 5 NULL 001000

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Data Types nhận dự án làm có lương

    SQL – Data Types

    Table of content


    What are SQL Data types?

    An SQL data type refers to the type of data which can be stored in a column of a database table. In a column, the user can store numeric, string, binary, etc by defining data types. For example integer data, character data, monetary data, date and time data, binary strings, and so on.

    While creating a in a database, we need to specify following two attributes to define a table column:

    • Name of the column
    • Data type of the column
    A database table”s column defines the data, whereas database table rows populate data into the table.

    For example, if you want to store student name in a column then you should give column name something like student_name and it”s data type will be char(50) which means it can store a string of characters up to 50 characters.

    The data type provide guidelines for to understand what type of data is expected inside each column, and hence, prevents the user from entering any unexpected or invalid data in a column. For example, if we want a column to store only integer values, we can specify its data types as INT. SQL will show an error if any other value apart from an integer is inserted into that particular column.

    Different RDBMS supports different type of data types to define their tables. This SQL Data types tutorial will list down different data types available in MySQL, Oracle, MS SQL Server, and MS Access databases.

    Defining a Data Type

    SQL Data types are defined during the creation of a table in a database. While creating a table, it is required to specify its respective data type and size along with the name of the column.

    Following is the syntax to specify a data type in MySQL −

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

    Let us look at an example query below to understand better.

    CREATE TABLE Customers (Name VARCHAR (25), Age INT);
    

    In the above SQL query, we are creating a table Customers. And since the Name column only stores string values, we are specifying its data type as “VARCHAR”. The VARCHAR data type represents string values in SQL. Similarly, we define the Age column with the integer data type, “INT”.

    When we assign the appropriate data type to a column, we can make efficient use of memory by allocating only the amount of system memory required for the data in the relevant column.

    Types of SQL Data Types

    There are three main types of SQL data types available in any RDBMS. They are listed below −

    • String
    • Numeric
    • Date and Time

    Data Types in MySQL, SQL Server, Oracle, and MS Access Databases

    Let”s discuss the data types in MySQL, SQL Server, Oracle (PL/SQL) and MS Access Databases in detail. All the three main types (String, Numeric, Date and Time) of SQL data types explained below-

    MySQL Data Types

    There are three main data types available in Database: string, numeric, and date and time. Following section lists down all the data types available in MySQL Version 8.0

    MySQL – String Data Types

    Data type Description
    CHAR(size) A fixed length string which can have letters, numbers, and special characters. The size parameter specifies the column length in characters which can vary from from 0 to 255. Default size is 1
    VARCHAR(size) A variable length string which can contain letters, numbers, and special characters. The size parameter specifies the maximum string length in characters which can vary from 0 to 65535.
    BINARY(size) This is equal to CHAR(), but stores binary byte strings. The size parameter specifies the column length in bytes. Default size is 1
    VARBINARY(size) This is equal to VARCHAR(), but stores binary byte strings. The size parameter specifies the maximum column length in bytes.
    TINYTEXT This holds a string with a maximum length of 255 characters
    TEXT(size) This holds a string with a maximum length of 65,535 bytes
    LONGTEXT This holds a string with a maximum length of 4,294,967,295 characters
    TINYBLOB This represents a small BLOBs (Binary Large Objects). Max length is 255 bytes
    BLOB(size) This represents a BLOBs (Binary Large Objects). Holds up to 65,535 bytes of data
    MEDIUMTEXT This holds a string with a maximum length of 16,777,215 characters
    MEDIUMBLOB This represents a medium BLOBs (Binary Large Objects). Holds up to 16,777,215 bytes of data
    LONGBLOB This represents a large BLOBs (Binary Large Objects). Holds up to 4,294,967,295 bytes of data
    ENUM(val1, val2, val3, …) A string object that can contain 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

    MySQL – Numeric Data Types

    Data type Description
    INT A normal-sized integer that can be signed or unsigned. If signed, the allowable range is from -2147483648 to 2147483647. If unsigned, the allowable range is from 0 to 4294967295. You can specify a width of up to 11 digits.
    TINYINT A very small integer that can be signed or unsigned. If signed, the allowable range is from -128 to 127. If unsigned, the allowable range is from 0 to 255. You can specify a width of up to 4 digits.
    SMALLINT A small integer that can be signed or unsigned. If signed, the allowable range is from -32768 to 32767. If unsigned, the allowable range is from 0 to 65535. You can specify a width of up to 5 digits.
    MEDIUMINT A medium-sized integer that can be signed or unsigned. If signed, the allowable range is from -8388608 to 8388607. If unsigned, the allowable range is from 0 to 16777215. You can specify a width of up to 9 digits.
    BIGINT A large integer that can be signed or unsigned. If signed, the allowable range is from -9223372036854775808 to 9223372036854775807. If unsigned, the allowable range is from 0 to 18446744073709551615. You can specify a width of up to 20 digits.
    FLOAT(M,D) A floating-point number that cannot be unsigned. You can define the display length (M) and the number of decimals (D). This is not required and will default to 10,2, where 2 is the number of decimals and 10 is the total number of digits (including decimals). Decimal precision can go to 24 places for a FLOAT.
    DOUBLE(M,D) A double precision floating-point number that cannot be unsigned. You can define the display length (M) and the number of decimals (D). This is not required and will default to 16,4, where 4 is the number of decimals. Decimal precision can go to 53 places for a DOUBLE. REAL is a synonym for DOUBLE.
    DECIMAL(M,D) An unpacked floating-point number that cannot be unsigned. In the unpacked decimals, each decimal corresponds to one byte. Defining the display length (M) and the number of decimals (D) is required. NUMERIC is a synonym for DECIMAL.

    MySQL – Date and Time Data Types

    Data type Description
    DATE A date in YYYY-MM-DD format, between 1000-01-01 and 9999-12-31. For example, December 30th, 1973 would be stored as 1973-12-30.
    DATETIME A date and time combination in YYYY-MM-DD HH:MM:SS format, between 1000-01-01 00:00:00 and 9999-12-31 23:59:59. For example, 3:30 in the afternoon on December 30th, 1973 would be stored as 1973-12-30 15:30:00.
    TIMESTAMP A timestamp between midnight, January 1st, 1970 and sometime in 2037. This looks like the previous DATETIME format, only without the hyphens between numbers; 3:30 in the afternoon on December 30th, 1973 would be stored as 19731230153000 ( YYYYMMDDHHMMSS ).
    TIME Stores the time in a HH:MM:SS format.
    YEAR(M) Stores a year in a 2-digit or a 4-digit format. If the length is specified as 2 (for example YEAR(2)), YEAR can be between 1970 to 2069 (70 to 69). If the length is specified as 4, then YEAR can be 1901 to 2155. The default length is 4.

    MS SQL Server Data Types

    As we have previously discussed in this chapter, there are three main data types in MS SQL server. They are: string, numeric, and date and time.

    MS SQL Server – String Data Types

    String data types in SQL allow us to store a group of characters, enclosed in single quotes, in a record of a table column. These characters can be of any type: numerals, letters, symbols etc.

    Users can either store a fixed number of characters or a variable number of characters, depending on their preferences.

    Following is the list of the data types that are included under the string data types in SQL.

    Data type Description
    char(n) It holds the character string with the fixed width. Maximum size of this data type is 8000 characters.
    varchar(n) It holds the character string with the variable width. Maximum size of this data type is also 8000 characters.
    varchar(max) It holds the character string with the variable width. Maximum size of this data type is 1073741824 characters.
    text It holds the character string with the variable width. This data type can store up to maximum of 2GB text data.
    nchar It holds the Unicode string with the fixed width. Maximum size of this data type is also 4000 characters.
    nvarchar It holds the Unicode string with the variable width. Maximum size of this data type is also 4000 characters.
    ntext It holds the Unicode string with the variable width. This data type can store up to maximum of 2GB text data.
    binary(n) It holds the binary string with the fixed width.
    varbinary It holds the binary string with variable width. Maximum size of this data type is also 8000 bytes.
    varbinary(max) It holds the binary string of max length of variable width. Maximum size of this data type is 2 GB.
    image It holds the variable length of the data type that can store binary data. Maximum size of this data type is 2 GB.
    Nvarchar(max) It holds the Unicode string of max length of variable width. Maximum size of this data type is 536870912 characters.

    Example

    In the following example, we are creating a table “students” with only string data types values: varchar and char.

    CREATE TABLE students (
      name varchar(20) NOT NULL,
      gender char(6) NOT NULL,
      city text NOT NULL
    );
    

    Output

    On executing the query, the output will be displayed as −

    (0 rows affected)
    

    Verification

    On the execution of the SQL queries “EXEC sp_help ”dbo.students” we get the details of the table and the data types of each column.

    Column_name Type Computed Length Prec Scale Nullable
    name varchar no 20 no
    gender char no 6 no
    city text no 16 no

    MS SQL Server – Numeric Data Types

    Numeric data types are one of the most widely used data types in SQL. They are used to store numeric values only.

    Following is the list of data types that are included under the numeric data types in SQL.

    Data type Description
    bit It holds the integer that can be 0, 1 or NULL.
    tinyint It allow to holds the whole number from 0 to 255.
    smallint It allow to holds the number between -32,768 and 32,767.
    int It allow to holds the whole number between -2,147,483,648 and 2,147,483,647.
    bigint It allow to holds the whole number between -9,223,372,036,854,775,808 and 9,223,372,036,854,775,807
    decimal(p, s)

    It is fixed precision and scale numbers. That allow numbers from -10^38 + 1 to 10^38-1.

    The p parameter indicates the maximum total number of digits that can be stored on both sides of the decimal point, left and right. It must have a value from 1 to 38. By default, it is 18.

    The s parameter indicates the maximum number of the digit to the right of the decimal point. S must be a value from 0 to p. The value is set to 0 by default.

    numeric(p, s)

    It is fixed precision and scale numbers. That allow numbers from -10^38 + 1 to 10^38-1.

    The p parameter indicates the maximum total number of digits that can be stored on both sides of the decimal point, left and right. It must have a value from 1 to 38. By default, it is 18.

    The s parameter indicates the maximum number of the digit to the right of the decimal point. S must be a value from 0 to p. The value is set to 0 by default.

    smallmoney It holds the monetary data from -214,748.3648 to 214,748.3647.
    Money It holds the monetary data from -922,337,203,685,477.5808 to 922,337,203,685,477.5807.

    Float(n)

    It holds or store the floating precession number data from -1.79E + 308 to 1.79E + 308.

    The n parameter indicates whether the field should hold 4 or 8 bytes. Float(24) contains a 4-byte field, while Float(53) contains an 8-byte field. The default value of n is 53.

    real It holds the floating precision number data from -3.40E + 38 to 3.40E + 38.

    Example

    In the following example, we are creating a table named employees with only numeric data type values.

    CREATE TABLE employees (
      ID int NOT NULL,
      myBoolean bit NOT NULL,
      Fee money,
      celsius float NOT NULL
    );
    

    Output

    On executing the query, the output will be displayed as −

    (0 rows affected)
    

    Verification

    On the execution of the SQL queries “EXEC sp_help ”dbo.employees;” we get the details of the table and the data types of each column.

    Column_name Type Computed Length Prec Scale Nullable
    ID int no 4 10 0 no
    myBoolean bit no 1 no
    Fee money no 18 19 4 yes
    Celsius float no 8 53 NULL no

    MS SQL Server – Date and Time Data Types

    datetime data types are used in SQL for values that contain both dates and times. datetime and time values are defined in the formats: yyyy-mm-dd, hh:mm:ss.nnnnnnn (n is dependent on the column definition) respectively.

    Following is the list of data types that are included under the date and times data types in SQL.

    Data type Description
    datetime It stores date and time both from January 1, 1753 to December 31, 9999 with an accuracy of 3.33 milliseconds.
    datetime2 It stores date and time both from January 1, 0001 to December 31, 9999 with an accuracy of 100 nanoseconds.
    smalldatetime It stores date and time both from January 1, 1900 to June 6, 2079 with an accuracy of 1 minute.
    date It stores date only from January 1, 0001 to December 31 9999.
    time It store time only to an accuracy of 100 nanoseconds.
    datetimeoffset It is the same of the datetime2 with the addition of the time zone offset.
    timestamp It stores the unique number that gets updated every time a row gets created or modified. It does not correspond to real time and is based on internal time. Each table may have only one timestamp variable.

    Note − Here, datetime has 3.33 milliseconds accuracy where as smalldatetime has 1 minute accuracy.

    Example

    In the following example, we are creating a table named Cust_details with only date and time data types values.

    CREATE TABLE Cust_details (
      HolidayDate DATE NOT NULL,
      OrderDateTime DATETIME,
      ScheduleFrom TIME NOT NULL,
      ShippingDateTime DATETIME2
    );
    

    Output

    On executing the query, the output will be displayed as −

    (0 rows affected)
    

    Verification

    On the execution of the SQL queries “EXEC sp_help ”dbo.Cust_details;” we get the details of the table and the data types of each column.

    Column_name Type Computed Length Prec Scale Nullable
    HolidayDate date no 3 10 0 no
    OrderDateTime datetime no 8 yes
    ScheduleFrom time no 5 16 7 no
    ShippingDateTime datetime2 no 8 27 7 yes

    Note:

    • If you are using the MySQL workbench to run the SQL data types and their queries, then there are some SQL data types and formats for date and time that won”t work; like “money”, “datetime2”, “yyyy/mm/dd” and “time AM”. All these data types specified are compatible only with the SQL server.
    • The size of these data types may change in the future updates keep checking the SQL documentation.

    Oracle Data Types

    There are four main types of data types available in : string, numeric, date & time and large object data types. Following section lists down all the data types available in Oracle Database.

    Oracle – String Data Types

    Data type Description
    CHAR(size) It is used to store character data within the predefined length. It can be stored up to 2000 bytes.
    NCHAR(size) It is used to store national character data within the predefined length. It can be stored up to 2000 bytes.
    VARCHAR2(size) It is used to store variable string data within the predefined length. It can be stored up to 4000 byte.
    VARCHAR(SIZE) It is the same as VARCHAR2(size). You can also use VARCHAR(size), but it is suggested to use VARCHAR2(size)
    NVARCHAR2(size) It is used to store Unicode string data within the predefined length. We have to must specify the size of NVARCHAR2 data type. It can be stored up to 4000 bytes.

    Oracle – Numeric Data Types

    Data type Description
    NUMBER(p, s) It contains precision p and scale s. The precision p can range from 1 to 38, and the scale s can range from -84 to 127.
    FLOAT(p) It is a subtype of the NUMBER data type. The precision p can range from 1 to 126.
    BINARY_FLOAT It is used for binary precision( 32-bit). It requires 5 bytes, including length byte.
    BINARY_DOUBLE It is used for double binary precision (64-bit). It requires 9 bytes, including length byte.

    Oracle – Date and Time Data Types

    Data type Description
    DATE It is used to store a valid date-time format with a fixed length. Its range varies from January 1, 4712 BC to December 31, 9999 AD.
    TIMESTAMP It is used to store the valid date in YYYY-MM-DD with time hh:mm:ss format.

    Oracle – Large Object Data Types (LOB Types)

    Data type Description
    BLOB It is used to specify unstructured binary data. Its range goes up to 232-1 bytes or 4 GB.
    BFILE It is used to store binary data in an external file. Its range goes up to 232-1 bytes or 4 GB.
    CLOB It is used for single-byte character data. Its range goes up to 232-1 bytes or 4 GB.
    NCLOB It is used to specify single byte or fixed length multibyte national character set (NCHAR) data. Its range is up to 232-1 bytes or 4 GB.
    RAW(size) It is used to specify variable length raw binary data. Its range is up to 2000 bytes per row. Its maximum size must be specified.
    LONG RAW It is used to specify variable length raw binary data. Its range up to 231-1 bytes or 2 GB, per row.

    MS Access Data Types

    The MS Access database also offers four categories of data types: String, Numeric, Date and Time, and other specialized data types.

    Following are all data types that are provided by MS Access 2013 version and later.

    MS Access – String Data Types

    Data type Description
    Short Text (formerly “Text”) It is a string data type that holds Alphanumeric data, like, names, titles, etc. It can hold up to 255 characters.
    Long Text (formerly “Memo”) It is also a string data type which holds Large Alphanumeric data, like paragraphs, etc. It can hold up to 1GB or 64,000 characters.

    MS Access – Numeric Data Types

    Data type Description
    Number It only holds Numeric data. The size can range from 1 to 16 bytes.
    Large Number It also holds numeric data. The maximum size of this data type is 8 bytes.

    MS Access – Date and Time Data Types

    Data type Description
    Date/Time It holds date and time data. The maximum size of this data type is 8 bytes.
    Date/Time Extended It also holds date and time data. The maximum size of this data type is Encoded string of 42 bytes.

    MS Access – Specialized Data Types

    Data type Description
    Currency This data type stores Monetary data, with up to 4 decimal places of precision. The size of this data type is 8 bytes.
    AutoNumber This stored a unique value that is generated by MS Access for each new record. The size of this data type is 4 bytes.
    Yes/No It holds Boolean data in the form of 0 and 1. ”0” for false and ”-1” for true. The maximum size is 1 byte.
    OLE Object It stores pictures, graphs or other ActiveX object from another Window-based application. The size can be stored up to 2GB.
    Hyperlink It stores a link address to a document or file on the Internet, on an intranet, on a local area network (LAN), or on your local computer. The size can go up to 8,192 characters.
    Attachment The attachment data type in MS Access allows the user to attach such as pictures, documents, spreadsheets, or charts. It can have unlimited number of attachments per record; but only up to the storage limit of the size of a database file.
    Calculated With this data type, you can create an expression that uses data from one or more fields. Then, from this expression, a result data type can also be created. However, this data type isn”t available in MDB file formats. The size of this data type can vary depending on the result type.
    Lookup Wizard The Lookup Wizard is not technically a data type. But when this entry is chosen, a wizard starts to help the user define a lookup field. The size of this data type depends on the size of the lookup field.

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc

  • Khóa học miễn phí SQL – Expressions nhận dự án làm có lương

    SQL – Expressions

    Table of content


    What is SQL Expression?

    An SQL expression is a combination of one or more values, operators and SQL functions that are all evaluated to a value. These SQL EXPRESSION(s) are like formulae and they are written in query language. You can also use them to query the database for a specific set of data.

    Expressions are used in WHERE clause of an SQL query. As you might have already known, a WHERE clause specifies a condition that needs to be satisfied for the purpose of filtering records from a database table. This condition is comprised of either single or multiple expressions. These expressions are further classified into three types −

    • Boolean Expressions
    • Numeric Expressions
    • Date and time Expressions

    Let us discuss each of these expressions in detail further in this chapter.

    Syntax

    Consider the basic syntax of the SELECT statement containing some expressions as follows −

    SELECT column1, column2, columnN
    FROM table_name
    WHERE [CONDITION|EXPRESSION];
    

    SQL Boolean Expressions

    SQL Boolean Expressions are SQL expressions that return only Boolean Datatype as a result. These expressions can be of two types −

    • Boolean Expressions that check for equality of two values using SQL comparison operators. Here, equality of these values is a condition.
    • Boolean Expressions can also contain one value paired with an SQL logical operator. In this case, the logic specified acts like a condition.

    They return either TRUE, FALSE or UNKNOWN as the result. If the condition is met, these expressions return TRUE; and FALSE otherwise. UNKNOWN is returned when either of the operands in the expression is a NULL value.

    Syntax

    Following is the syntax of Boolean Expression −

    SELECT column1, column2, columnN
    FROM table_name
    WHERE BOOLEAN EXPRESSION;
    

    Example

    Consider the CUSTOMERS table having the following records −

    ID NAME AGE ADDRESS SALARY
    1 Ramesh 32 Ahmedabad 2000.00
    2 Khilan 25 Delhi 1500.00
    3 kaushik 23 Kota 2000.00
    4 Chaitali 25 Mumbai 6500.00
    5 Hardik 27 Bhopal 8500.00
    6 Komal 22 Hyderabad 4500.00
    7 Muffy 24 Indore 10000.00

    The following query is a simple example showing the usage of an SQL Boolean Expression −

    SELECT * FROM CUSTOMERS WHERE SALARY = 10000;
    

    Output

    The output will be displayed as −

    ID NAME AGE ADDRESS SALARY
    7 Muffy 24 Indore 10000.00

    SQL Numeric Expressions

    SQL Numeric expressions are comprised of two operands and an SQL Arithmetic Operator. These expressions are used to perform any mathematical operation in any query. Hence, the operands must always be numerals and the return value will always be a number as well.

    Syntax

    Following is the syntax −

    SELECT numerical_expression as OPERATION_NAME
    FROM table_name
    WHERE NUMERICAL EXPRESSION ;
    

    Here, the numerical_expression is used for a mathematical expression or any formula.

    Example

    Following is a simple example showing the usage of SQL Numeric Expressions −

    SELECT 15 + 6;
    

    Output

    The output table is retrieved as −

    21
    

    Example

    There are several built-in functions like avg(), sum(), count(), etc., to perform what is known as the aggregate data calculations against a table or a specific table column.

    SELECT COUNT(*) FROM CUSTOMERS;
    

    Output

    The output is displayed as follows −

    7
    

    SQL Date Expressions

    SQL Date Expressions are used to compare date related values with current system date and time values. For instance, in a manufacturing company, items manufactured per year can be segregated by using date expressions in a WHERE clause. Counting from the first day of an year to the last day, the count of each item will be retrieved; once the required information is gathered, the company can use this information for their own purposes.

    Syntax

    Following is the syntax −

    SELECT column_name(s)
    FROM table_name
    WHERE DATE EXPRESSION ;
    

    Example

    In this example we are trying to simply retrieve the current timestamp of the system using CURRENT_TIMESTAMP.

    SELECT CURRENT_TIMESTAMP;
    

    Output

    The output table is displayed as −

    Current_Timestamp
    2009-11-12 06:40:23

    Example

    Consider the following Customer Order records in an ORDERS table:

    ORDER_ID CUSTOMER_ID DATE ORDER_AMOUNT ITEM_COUNT
    102 3 2009-10-08 00:00:00 3000 4
    100 3 2009-10-08 00:00:00 1500 2
    101 2 2009-11-20 00:00:00 1560 7
    103 4 2008-05-20 00:00:00 2060 3

    Now let”s retrieve the records before 1st June, 2008:

    SELECT * FROM ORDERS WHERE DATE < ''2008/06/01
    

    Output

    The output table is displayed as −

    ORDER_ID CUSTOMER_ID DATE ORDER_AMOUNT ITEM_COUNT
    103 4 2008-05-20 00:00:00 2060 3

    Khóa học lập trình tại Toidayhoc vừa học vừa làm dự án vừa nhận lương: Khóa học lập trình nhận lương tại trung tâm Toidayhoc