SQL Table

Table SQL Server: In the post, we will discuss the concept of an SQL table, a fundamental component of relational databases used to organize and store data in a structured format. The SQL tables consist of rows and columns, each row represents a specific record, and each column represents a specific attribute.

One of the important reasons for using a table sql server is it will provide a flexible and scalable way to store large amounts of data, making them an essential component of any data-driven application. As a result, having a solid understanding of SQL table design and best practices is critical for any SQL developer or data professional. Properly designing and structuring SQL tables can lead to faster query performance, more efficient data retrieval, and ultimately better decision-making based on the data stored within them.

We can store various SQL data types using the table SQL, including text, numeric, date/time, and binary data. They can store information about customers, products, orders, invoices, and other business-related data. Also, we can link multiple SQL tables together by using primary and foreign keys to establish relationships between different tables in a database. Primary keys are unique identifiers for each record in a table, while foreign keys are used to reference records in other tables.

The table sql server is essential for data manipulation and retrieval using SQL queries. In SQL queries, we use various SQL commands such as SELECT, INSERT, UPDATE, and DELETE can be used to retrieve, add, modify, or delete data from a table.

Before we start discussing in detail about SQL Table, let us try to understand a few other concepts like below:

What Is a Database Table?

If you’re wondering what a relational database model is, it’s one of the most commonly used data models for storing and processing data. Tables are essential elements of any database; in this context, tables refer to the database objects that hold the data in relational databases. A single database can contain one or more tables, which can all be modeled as relations.

Tables are similar to folders in a file system, where each table stores a collection of information. For data to be stored in a table, it must first be converted into rows and columns. Columns are the vertical sections of a table, and each column has a name and associated data type. Rows are the horizontal sections of a table, and each row contains one or more values that correspond to the columns in which they appear.

SQL Table 1

What is a Field in a Database?

A database is a collection of tables. Each table has many cells, which contain important pieces of information. The cells are arranged in rows and columns. The rows are called records. They hold information about one object (like a customer or an order). The columns are called fields. They hold details like ID, color, and zip code.

Fields in SQL

For example, if we have taken a customer record containing their name, address, and telephone number. Then each of these pieces of information is treated as a Field. And when we collect all the fields of a row is called a Record.

What is a Field in a Database - Fields in SQL

Records in SQL

A field on its own does not provide enough information to come to a conclusion. However, multiple fields can give context and meaning to the data. For example, if you have a field that lists colors and one of the cells says “red,” “green,” and “yellow,” it wouldn’t mean anything unless you knew what those colors represent or how they are related.

SQL Table 2

Various Table Operations

After discussing the Database and SQL table, we believe you got to know the importance of both the database and table. But in this post, we are going into detail about various operations we can perform in a table.

Here are the various operations which we are going to discuss in this post:

We are going to discuss all those functions in sequential order so that it will help you to understand the functionality easily. Let’s start with the Create table.

Before we proceed with how we can create an SQL create table in database, On your machine, SSMS (SQL Server Management Studio) should be available, and a database should have been created already. If the database is not created on your machine, you can follow our blog post where we discussed SQL Database in detail.

The below SQL queries are executed on the below configuration; based on your configuration, you may receive a different result. So before raising a flag, verify a few pieces of information.

SQL Server Management Studio 19.0.20179.0+4bc80247
SQL Server Management Objects (SMO) 16.200.48028.0+1d352ca4ec6e86337148c658706ab22ceb133f98
Microsoft T-SQL Parser 16.0.22524.0+62eedb15cd3cde34e51c8fbbdf9b06e575ec912e
Microsoft Analysis Services Client Tools 16.0.19970.0
Microsoft Data Access Components (MDAC) 10.0.19041.2486
Microsoft MSXML 3.0 5.0 6.0
Microsoft .NET Framework 4.0.30319.42000
Operating System 10.0.19044

SQL Create Table In Database

In this section of the sql create table database section, we will learn how to create a SQL table with examples. As mentioned above, we can have one or many columns in a table, and each column has an associated SQL data type that defines the data type that column can store.

Before we start how to create an SQL table in an SQL server, you know various SQL data types. For this, we have mentioned frequently used data types.

Data TypeDescriptionExample
IntStores number types11,25
Varchar(s) Stores a variable character with a max value of ‘s’Name(20) takes up to 20 characters
TextStores 6555 charactersIt doesn’t specify the maximum length of the characters. We can store paragraph content.
BooleanStores a binary typeEx: T or F
DateIt gives the date formatE.g., 2023-01-26

How To SQL Create Table In Database?

To create a table, we have to use the CREATE TABLE statement. And the syntax for the CREATE TABLE command is below:

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

Now, by following the above create table syntax, we will create a table whose name will be a student, and the table has the columns like Roll_Number, Name, Address, DOB, etc.

SQL Table 3

Note: We must provide data types for each column while creating a table. 

Create Table IF NOT EXIST SQL

When you are creating a table with a name, and at the same time, already table with the same name is present in the database, then you will get the below error:

There is already an object named ‘STUDENT’ in the database.

SQL Table 4

Previously we are using the Create Table IF NOT EXIST command by executing. What it was doing earlier is first, it will verify the database if a table is already present or not, And if there is no table present with the mentioned name, then it creates a new table with the mentioned name. But if we try with the latest versions of SSMS, you will get the below error:

CREATE TABLE IF NOT EXISTS STUDENT
(
Roll_Number int,
Name VARCHAR(25), 
Address TEXT, 
DOB DATE
);
SQL Table 5

But we can avoid this error by using Create Table IF NOT EXIST while creating a table, and for that, the query will be like below:

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES 
WHERE TABLE_NAME = N'STUDENT')
BEGIN
  PRINT 'Table Exists'
END
SQL Table 6

Create Table As In SQL Server

You can create a new table using records from any existing table using the CREATE TABLE AS command. For Example:

But when we try with the below SQL query syntax, we get this error:

CREATE TABLE DupSTUDENT
AS 
(
SELECT *
FROM STUDENT
);
SQL Table 7

Because Create Table As In SQL Server is no more supported, you can get a detailed article by following this link.

But still, do we have an option for creating a new table with all the records of an existing column by following the below query?

SELECT * INTO New_Table 
FROM YourTable
SQL Table 8

With this, we cover all the operations of SQL Create Table In Database. Now we will proceed to other important operations: how can we SQL rename the table?

SQL Rename Table

We are in the previous section, and we learn how to create a table. But in some cases, the database administrator or a user wants to change the name of an existing table with a new meaning; to give a proper name to the table.

There is no direct way to rename a table in SQL Server. However, you can use the sp_rename stored procedure to change the name of a table.

Here is the syntax for Rename a table name:

EXEC sp_rename 'old_table_name', 'new_table_name'

Note: Remember to enclose both the old and new names of the table in single quotations when you change it.

Example of SQL Rename SQL Table:

During Explain of How To Create an SQL Table In the SQL Server? We have created a table called “STUDENT.” But now let us rename the table “STUDENT” to “MCASTUDENT.”

EXEC sp_rename 'old_table_name', 'new_table_name'
SQL Table 9

When we have executed the above query, the SQL Table or SQL server will return you a message:

Caution: Changing any part of an object name could break scripts and stored procedures.

We are getting the above message, but the table has been renamed successfully.

SQL ALTER TABLE

If, after creating a table, you realize that you forgot to mention a column or constraint or specified the wrong name for the column, Or if the business changes the requirement, you must modify the table’s structure, don’t worry!

In that case, to modify the table’s structure, you can use the SQL Alter Table command to modify the structure of an existing table. With the help of Alter command, you can perform the below operations:

Let’s try to understand how to perform these operations one by one.

Alter Table Add Column

You can use the ALTER TABLE command with the ADD clause to add a column to a SQL Table. The command can add one or many columns to an existing table.

ALTER TABLE Customers
ADD phone varchar(10);

The above command will add the phone number column to the Customers table.

Alter Table Add Multiple Columns SQL Server

We can also add multiple columns at once. By following the below syntax:

ALTER TABLE table_name
  ADD (column_1 column_definition,
       column_2 column_definition,
       ...
       column_n column_definition);

Let’s take an example and add two columns Phone and age.

ALTER TABLE Customers
ADD phone int,  address text;
SQL Table 10

After adding the two columns, when we check the column in the customer, it will be displayed like this:

SQL Table 11

Alter Table Change Data Type

If you need to change the data type for a column, you can use the ALTER TABLE command with the MODIFY or ALTER COLUMN clause. Here is the syntax for the SQL Change Data Type or modify column in a SQL Table :

ALTER TABLE table_name
ALTER COLUMN column_name column_type;
ALTER TABLE Customers
ALTER COLUMN address VARCHAR(25);
SQL Table 12

In the above example, we have changed the datatype of the address column from text to VARCHAR. If you want to confirm the current data type of the address column, then you can execute the below command.

EXEC sp_help <Table Name>;

Executing the above command by entering the correct table name will display all the column names and their respective data types.

SQL Table 13

Alter Table Rename Column

You can use the ALTER TABLE command with the RENAME COLUMN clause if you need to rename a column. Below is the syntax:

sp_rename 'table_name.old_column', 'new_name', 'COLUMN';

Here is the query

sp_rename 'Customers.address', 'add', 'COLUMN';
SQL Table 14

With the help of the above query, we are changing the name of the address column to add.

Alter Table Drop Column Sql Server

If any other database objects no longer need a column in your table, you may remove that column from your table. This will help clean up your database and make it more efficient. To perform this operation, you can follow the below syntax:

ALTER TABLE table_name
DROP COLUMN column_name;

To understand Drop A Column In SQL, let’s go through with an example:

ALTER TABLE Customers
DROP COLUMN add1;
SQL Table 15

Above, we have discussed a few SQL alter commands, But in a separate post, we discuss all possible uses of SQL Alter Table commands in detail one by one. You can check by following the link.

SQL DELETE TABLE

The Delete command in SQL is a part of the Data Manipulation Language (a sub-language of SQL for data modification). This helpful tool can delete specific records based on conditions you set or all records from an entire table.

To delete only specified rows from a table, we need to use the WHERE clause in the DELETE statement, and If we forget to include the WHERE clause, it will delete all of the existing table’s rows.

One must be fully confident using this command, as it will forever erase the data.

Before starting the Delete command, you have to know the syntax:

DELETE FROM table_name [WHERE condition];  

If you write the SQL queries like the one below, all the records will be permanently deleted.

DELETE FROM table_name;

To Understand this, let’s take some examples; for this, we will take the help of a product table.

SQL Table 16

Let’s try to delete the “Apple” product, and here is the code:

Delete From products where product_name='Apple';
Delete Specific Record

After deleting the specific record, here are the table details:

SQL Table 17

SQL TRUNCATE TABLE

The SQL command TRUNCATE is a data definition language (DDL) statement that eliminates all the information from a database table without deleting it. It clears up room in the table and processes much faster than other deletion methods, but it cannot be reversed in many databases, so caution must be used when using this feature. Additionally, because of its DDL nature, no commit is needed after execution; it commits on its own at the end of execution.

The syntax for SQL TRUNCATE TABLE is:

TRUNCATE TABLE table_name;

Let’s take an example and will try to understand:

We have a Product table, and the table looks like it did before running the truncate SQL command:

SQL Table 18

Now let’s run the truncate table statement on the product table to remove all the records, and the truncate table SQL is below:

TRUNCATE TABLE products;
SQL Table 19

Let’s Check the SQL Table records after executing the truncate SQL query.

SQL Table 20

SQL DROP TABLE

When constructing tables, it is possible to make errors in the information provided. This could be anything from a table title or column name data type the column. In some situations, an older table might have been created that no longer meets current requirements but still has to remain with its same name or must be deleted for memory purposes. There may also be other scenarios that prompt us to delete existing tables and construct them as new.

How To Drop Table In SQL?

The DROP TABLE command can delete an existing SQL Table in a database. This statement will delete all the information, structure, and any associated relationships or permissions.

Here is the syntax for the Drop SQL Table:

DROP TABLE Table_Name;

Now let us go with an example of drop table SQL. Check the below query:

DROP TABLE products;

Once we have executed the above drop table SQL statement, the products table will be deleted from the database.

  • Always take a backup of the data before dropping a table, as the data in the table will be lost permanently once the table is dropped.
  • Ensure that you have admin or DROP permission to run the DROP TABLE command.

DROP TABLE IF EXISTS

Above, an error will be displayed if a table doesn’t exist when you try to drop it. To prevent this from happening, adding the optional IF EXISTS command while dropping the table can fix the problem.

For example, we have already dropped the products table, but if we rerun the drop query, we will get the below message.

Invalid object name ‘products’.

but if we try with the IF EXISTS command, then we are not going to get the warning message; that time, we get the below message

Commands completed successfully.

SQL Table 21

SQL COPY TABLE

It is possible to take the data from one SQL table and duplicate it into another within the same server using the SELECT INTO statement in SQL.

Here is the syntax of sql select into insert:

SELECT * INTO New_table_name FROM old_table_name;  

Let’s see how we can use the sql select in the insert command. Lets we have a product table with the below details.

SQL Table 22

Suppose you want to copy the records of the products table into the products_details table. So to do this, here is the below query:

SELECT * INTO products_details FROM products;

To Verify this, the products_details table is created and has all the records of the products table. We can run the below command:

Select * from products_details;

When you run the above SELECT statement in SQL, we can see all the records of products in the products_details table.

CREATE TEMP TABLE SQL SERVER

A table in SQL Server that is not permanently stored on the database server and only exists temporarily during a particular session is known as a temp table. This type of table stores just part of the data from an ordinary one, but it can be used multiple times within its defined period. Temp tables cannot remain in memory; once the current user has disconnected or ended their session, they will automatically be removed from “tempdb”.

Creating a temporary table can be helpful when we need to deal with many records. This way, we can filter from the huge data and store only what we need in this table so that when we run queries, it’s faster than having to sort through all the information repeatedly. This way, complex tasks are easier to do quickly using its features.

Different Way to Create Temp Table Sql Server

We can Create Temp Table Sql Server in two ways, which are

  • SELECT INTO Statements
  • CREATE TABLE Statements

Here is our Permanent Table: Employee with all records

SQL Table 23

Now we see how to create a temp table sql server in both ways:

Create Temp Table Sql Server By Using SELECT INTO Statements

The SELECT INTO statement is the most straightforward way to form a temporary SQL server table. We have also previously discussed how to transfer one table value into another with the help of the SELECT INTO statement. But we can also be used for repeated use of intermediate results within the same session.

The syntax for Create Temp Table Sql Server By Using SELECT INTO Statements

 SELECT select_list  
 INTO temporary_table_name  
 FROM regular_table_name  
 WHERE conditions;  

A temp table’s name always begins with a hashtag (#). This indicates to SQL Server that the table is temporary.

Let’s take an example of creating a Temporary table using an SQL server using the SELECT INTO statement. For creating a temporary table, we are using the employees table.

SELECT first_name, last_name,   dept_id
INTO #501Dept  
FROM employees  
WHERE dept_id = 501;

Executing the above query will create a temporary table name #501Dept, with three columns (first_name, last_name, and dept_id) derived from the SELECT statements. These data will be populated from the table employees and contain all the dept_id is 501 records first_name, last_name, dept_id.

After executing the statement, we can locate the temporary table in the mentioned path of the SQL Server Management Studio. Here is the path: Object Explorer -> Databases -> System Databases-> tempdb -> Temporary Tables. See the below figure:

Temporary Table

We can observe from the image that each temporary table has a sequence number at the end of its name. This indicates a unique ID, which helps the SQL server differentiate between tables with similar names by using this identifier. Creating such IDs is because many database connections may simultaneously have identical names for multiple temp tables.

We can also perform SQL operations on the temporary table like there is a requirement to get all the employees who have dept_id is 501. In this case, we can use table #501Dept, which has only those records with dept_id 501.

SQL Table 24

Create Temp Table Sql Server By Using CREATE TABLE Statement

The CREATE TABLE statement is a great way to craft a temporary table. And, with the below statement, we can make #501dept come alive!

CREATE TABLE #500Dept  
(  
   first_name VARCHAR(65),  
   last_name VARCHAR(65),
   dept_id INT,  
) 

If you see the above SQL queries, it’s like a normal create table statement. But this will create a temporary table, as we have mentioned # in the table name.

SQL Table 25

Here is a Temporary table created, but there are no records inside the table. Now we have to add the records to the temporary table. So to insert the records, we have to execute the below records:

INSERT INTO #500Dept  
SELECT first_name, last_name,   dept_id
FROM employees  
WHERE dept_id = 500;

After executing the above command, records will be copied into the temp table. See the below picture:

SQL Table 26

Conclusion:

In this blog post, we have discussed all various aspects of SQL Table in a detailed manner and the various operations such as Create, Rename, Alter, Delete, Truncate, Drop, and Temporary Table.

If you feel like this post still, we can add the missing topics, then you can inform us about those topics in the comment section.

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment