INSERTING DATA SQL
This week in my SQL journey I learned about how to insert data into table in a database. In this case I already have a database I have created called book_shop. I created this database by following along a curriculum that I found on Udemy. I already have MYSQL workbench connected with MYSQL terminal which makes it a lot more user friendly. In order to view the databases you have created in SQL you call the command SHOW DATABASES; and it shows all the databases that are currently in your DBMS. In the screenshot I attached you will see there is a book_shop and customer_orders which I have created. The other 4 are databases that default in every MYSQL database.
In SQL the command that is used to insert data is INSERT INTO <table_name, table_name> (column_name) VALUES (value, value);. The words that are capitalized are the actual SQL keywords and the other would just be the names of the table and columns you are using. The first parentheses after table_name is where you describe which columns you will be entering data. You can have as many column names as you want in parentheses as long as they are valid columns that exist in your table. However you must have the exact amount of values separated in the values as you do in the table names you are selecting. They must also be the same data type or you will get an error. For example if a column is takes in a name which would be a VARCHAR you would not enter an INTEGER like an age in that column. In the screenshot I attached I inserted a new author and title which I named after myself and the title of it is MYSQL Tutorial. Notice how the column names must be exact as the column names in the table or else you will get an error.
In the books table that I created you can also see that I only selected to insert into 3 columns however there are 7 columns in my table. This means that you dont have to insert into every single column every time you are going to insert a new row. When you dont make a selection for a column in your insert SQL statement SQL will automatically set that column to NULL. NULL simply means empty it does not mean 0. You however can alter this by adding a keyword when you first create your table called NOT NULL. This will make it to where you must insert that data when inserting a new row or you will get an error message that a certain row cannot be NULL. This is extremely useful when you are entering customer data and certain information is necessary. You can also set a keyword called DEFAULT when creating your table. This allows you to set what will be automatically entered into a row if certain row information is missing. For example if I were to insert a new book into my database and I did not enter the amount of pages that the book has instead of it saying NULL I can set a default to enter Unknown. This makes the table look much cleaner instead of having columns set to NULL.
Comments
Post a Comment