SQL

SQL Tables

SQL Tables

This page covers the implementation of SQL tables.

In SQL, data is stored inside tables. Each table has rows and columns, representing records and attributes, respectively.

The syntax for managing tables is easy and quite straightforward. The methods within this tutorial are:

  • create tables
  • drop tables

Create tables

In SQL, we use the keywords “create table” to create a new table.

When creating new tables, SQL requires the assignment of each column’s data type. This defines what will the column contain, together with all allowable features of the specific data type.

We define all columns inside round brackets, with each column separated by a comma.

Below is an example of creating a table.

CREATE TABLE student_names (
	id int,
	firstName varchar(50),
	lastName varchar(50),
	age int
);

# Output: Commands completed successfully.
idfirstNamelastNameage

The above statement creates a new (empty) table “student names”, with 4 columns (id, first name, last name, and age).

The id and age columns hold integer values and first and last names text (up to 50 characters).

We can check the list of tables with the statement below:

SELECT * FROM sys.tables;

Drop tables

Dropping a table is very straightforward as well. The keywords are “drop table”.

Please be careful when deleting tables, as all data disappears as well. The drop statement also deletes the structure of the table.

The following is an example of dropping (deleting) the “student names” table.

DROP TABLE student_names;

# Output: Commands completed successfully.

If successful, the execution deletes the table. To check the outcome, use the “SELECT * FROM sys.tables;”.

Truncate table

The “truncate table” statement is another method of deleting a table. But this statement deletes only the information inside the table, and not the table itself. Therefore, the structure of the table stays intact.

Below is an example of deleting a table with the “truncate” statement.

TRUNCATE TABLE student_names;

# Output: Commands completed successfully.

Now when the “SELECT * FROM sys.tables;” statement executes, the table is shown as present.


Next: SQL Alter