Page 19 - Modular_V2.0_SQL_Flipbook
P. 19

CREATING A TABLE

                 As you know that a table is a collection of organised data in the form of rows and columns. It is also
                 known as a relation. The CREATE TABLE command is used to create a table in SQL. The syntax to

                 create a table is:
                     CREATE TABLE table_name

                     (
                         column_name1 data_type (size),

                          column_name2 data_type (size),
                          column_name3 data_type (size),

                          .....
                          .....

                          column_nameN data_type (size)
                     );

                 While creating a table in SQL, it is necessary to give a data type for each field/column.

                 Let us create a table named Students having StudentId, FirstName, LastName, and Marks  fields in
                 the following way:
                     CREATE TABLE Students

                     (

                         StudentID INTEGER,
                         FirstName CHAR(30),

                         LastName CHAR(30),
                         Marks INT

                     );
                 In the preceding code, you have noticed that a value 30 is given with the CHAR data type within the
                 parentheses as its size. The meaning of 30 is that you can store a string value up to 30 characters in
                 the FirstName and LastName fields. Whether you store a single character or 30 characters, this field
                 will always occupy space for 30 characters regardless of the actual string length. If you store one

                 character, 29 blank spaces will be inserted with the character.

                 Applying Constraints in the Table

                 SQL constraints are used to define rules for table data. These rules control the data that can be
                 stored in a column. Constraints are used to restrict the types of data that can be entered into a table.

                 NULL Constraint

                 The NULL constraint allows a column to store the NULL value, which means that if the column
                 does not receive any value during insert or update operations, it will accept the values of the other

                 columns in insert operations without showing any error.


                                                                                                                     17
                                                                                               Introduction to MySQL
   14   15   16   17   18   19   20   21   22   23   24