Tables in sql
Tables in sql
The SQL CREATE TABLE statement is a foundational command used to define and structure a new
table in a database. By specifying the columns, data types, and constraints such as PRIMARY
KEY, NOT NULL, and CHECK, helps you design the database schema.
In this article, we’ll learn the syntax, best practices, and practical examples of using the CREATE
TABLE statement in SQL. We’ll also cover how to create tables from existing data and troubleshoot
common errors.
To create a new table in the database, use the SQL CREATE TABLE statement. A table’s structure,
including column names, data types, and constraints like NOT NULL, PRIMARY KEY, and CHECK, are
defined when it is created in SQL.
The CREATE TABLE command is a crucial tool for database administration because of these
limitations, which aid in ensuring data integrity.
Syntax:
Let’s look at examples of CREATE TABLE command in SQL and see how to create table in SQL.
In this example, we will create a new table and insert data into it.
Let us create a table to store data of Customers, so the table name is Customer, Columns are Name,
Country, age, phone, and so on.
LastName VARCHAR(50),
Country VARCHAR(50),
Phone int(10)
);
Output:
To add data to the table, we use INSERT INTO command, the syntax is as shown below:
Syntax:
Example Query
Output:
Create Table From Another Table
We can also use CREATE TABLE to create a copy of an existing table. In the new table, it gets the exact
column definition all columns or specific columns can be selected.
If an existing table was used to create a new table, by default the new table would be populated with
the existing values from the old table.
Syntax:
Query:
FROM customer;
Output:
Note: We can use * instead of column name to copy whole table to another table.
The DESC table_name; command can be used to display the structure of the created table
We can also add constraint to table like NOT NULL, UNIQUE, CHECK, and DEFAULT.
If you try to create a table that already exists, MySQL will throw an error. To avoid this, you
can use the CREATE TABLE IF NOT EXISTS syntax.
SQL DROP TABLE
The DROP TABLE command in SQL is a powerful and essential tool used to permanently delete a
table from a database, along with all of its data, structure, and associated constraints such as
indexes, triggers, and permissions. When executed, this command removes the table and all its
contents, making it unrecoverable unless backed up.
In this article, We will learn about SQL DROP TABLE by understanding its examples, and cover
important points to help you manage your database tables effectively.
The DROP TABLE statement in SQL is used to delete a table and all of its data from the
database permanently.
This operation cannot be undone, and once the table is dropped all data in that table is lost.
Once executed, this operation removes the table definition and all of its rows, so the table
can no longer be accessed or used.
This action is irreversible which means that once a table is dropped, it cannot be recovered
unless there is a backup.
Syntax:
The syntax of the command remains the same in Oracle, SQL Server and MySQL.
To demonstrate how to use the DROP TABLE command, let’s first create a database and a table, and
then we will drop it.
Step1: First, we will create a database and table on which the SQL queries will be run.
USE NewCafe;
VALUES
Output:
At this point, the categories table has been created with three rows of sample data.
Step2: Now, let’s use the DROP TABLE statement to delete the categories table permanently
Query:
Output:
The SQL DROP TABLE statement is used to delete tables in a database, along with all
associated data, indexes, triggers, constraints and permission specifications.
The table will be permanently disable, so use this query with caution.
Use DROP TABLE IF EXISTS query to prevent errors when dropping a table that does not exist
When dropping a partitioned table, the DROP TABLE statement removes the table definition,
all partitions, all data stored in those partitions, and all partition definitions.
The DROP TABLE statement can be used to drop temporary tables by including
the TEMPORARY keyword.
Conclusion
The DROP TABLE command is an essential SQL function that helps in maintaining and cleaning up
database environments. Its ability to permanently remove tables and all related data makes it a
powerful tool, but it should be used cautiously to avoid accidental data loss. Understanding its
syntax, options for error prevention, and its role in managing both regular and temporary tables is
key to effective database management.
The SQL DELETE statement is one of the most commonly used commands in SQL (Structured Query
Language). It allows you to remove one or more rows from the table depending on the situation.
Unlike the DROP statement, which removes the entire table, the DELETE statement removes data
(rows) from the table retaining only the table structure, constraints, and schema
In this article, we’ll learn the syntax and usage of the SQL DELETE statement with detailed examples,
including how to delete a single record, delete multiple records, and delete all records from a table.
The SQL DELETE statement removes one or more rows from a database table based on a condition
specified in the WHERE clause. It’s a DML (Data Manipulation Language) operation that modifies the
data within the table without altering its structure.
Syntax:
WHERE some_condition;
Parameter Explanation
Assume we have created a table named GFG_Employee in SQL which contains the personal details of
the Employee including their id, name, email and department etc. as shown below −
department VARCHAR(20)
);
Output
GFG_Employees
Example 1: Deleting Single Record
We can use the DELETE statement with a condition to delete a specific row from a table.
The WHERE clause ensures only the intended record is removed. We can delete the records named
Rithvik by using the below query:
Query:
Output:
Delete the rows from the table GFG_Employees where the department is “Development”. This will
delete 2 rows(the first row and the seventh row).
Query
Output
output
To remove all the entries from the table, you can use the following query:
Query:
Or
Output:
All of the records in the table will be deleted, there are no records left to display. The table
GFG_EMPLOyees will become empty.
output
Since the DELETE statement is a DML operation, it can be rolled back when executed in a statement.
If you accidentally delete records or need to repeat the process, you can use
the ROLLBACK command.
Query:
START TRANSACTION;
ROLLBACK;
Always Use a WHERE Clause: Avoid deleting all rows by accident. Always filter records using
a WHERE clause to specify which rows to delete.
Backup Data: Before performing large deletions, ensure that you have a backup of the data
to avoid irreversible loss.
Test on Development Server: Always test your DELETE queries on a development or staging
environment to ensure they produce the desired result.
Optimize Deletions: For large datasets, delete records in batches to reduce performance
impact.
Conclusion
The SQL DELETE statement is a powerful tool for removing data from a database table based on
specific conditions. By understanding the correct syntax, how to delete individual or multiple records,
and how to handle performance issues, you can use the DELETE statement efficiently and safely.
Always be careful when deleting data, especially when working with large tables or sensitive
information. By following best practices and using habits, you can ensure that your data remains
authentic and secure.
In SQL, making structural changes to a database is often necessary. Whether it’s renaming a table or
a column, adding new columns, or modifying data types, the SQL ALTER TABLE command plays a
critical role. This command provides flexibility to manage and adjust database schemas without
affecting the existing data.
In this article, we will explain how to rename tables and columns in SQL using the ALTER TABLE
command, along with practical examples. We’ll also cover how these commands vary across
databases like MySQL, MariaDB, and Oracle. This comprehensive guide ensures our queries
are accurate, efficient, and SEO-optimized.
The structure of an existing table can be changed by users using the SQL ALTER TABLE command. If
we need to rename a table, add a new column, or change the name of an existing column in SQL,
the ALTER command is crucial for making schema changes without affecting the data that is already
there. This is essential for tasks like:
Renaming a table.
Changing a column name.
Syntax
1. Renaming a Table
2. Renaming a Column
Below are practical examples to help us understand how to use the ALTER command effectively in
various scenarios. These examples includes renaming tables or columns, adding new columns,
or changing column data types.
Let’s insert some data and then perform ALTER operation to understand better about alter
command.
Output
Student Table
Change the name of column name to FIRST_NAME in table Student. To change the column name of
the existing table we have to use Column keyword before writing the existing column name to
change
Syntax
Query:
Output
Output
In this example, the table name Student is changed to Student_Details using the ALTER
TABLE command, making the name more descriptive and relevant to its content.
Query:
Output
Student_Details table
To add a new column to the existing table, we first need to select the table with ALTER
TABLE command table_name, and then we will write the name of the new column and its datatype
with ADD column_name datatype. Let’s have a look below to understand better.
Syntax
Query:
Output
output
In the example, the phone column is updated from VARCHAR(20) to BIGINT to store numerical data
more efficiently and ensure data integrity for phone numbers without unnecessary characters.
Syntax
Query:
Output
id name age email phone
Explanation:
The phone column now has a BIGINT data type, suitable for storing large numeric values.
Conclusion
The SQL ALTER TABLE command is an effective way to modify the structure of an already-existing
tables in a database. When necessary, we can use ALTER TABLE to rename the entire table, rename a
specific column in SQL, or change a column name to something more descriptive. This command is
important for database administration since it also enables the addition of new columns and
the modification of data types.
The DROP and TRUNCATE commands in SQL are used to remove data from a table, but they work
differently. Understanding the difference between these two commands is important for
proper database management, especially when dealing with large amounts of data.
This article provides an in-depth explanation of the DROP and TRUNCATE commands in SQL, their
main differences, usage, and detailed examples. By the end of this article, We will be ready to use
these commands effectively and understand their impact on your database.
Syntax:
DROP Table
Syntax:
DROP database
Syntax:
The TRUNCATE command is a Data Definition Language (DDL) action that removes all rows from a
table but preserves the structure of the table for future use. Although TRUNCATE is similar to the
DELETE command (without the WHERE clause), it is much faster because it bypasses certain integrity
constraints and locks. It was officially introduced in the SQL:2008 standard.
Syntax:
Where,
The key differences between DROP and TRUNCATE statements are explained in the following table:
DROP TRUNCATE
In the drop table data and its definition is deleted It preserves the structure of the table for
with their full structure. further use exist but deletes all the data.
DROP TRUNCATE
Integrity constraints get removed in the DROP Integrity constraint doesn’t get removed
command. in the Truncate command.
Drop query frees the table space complications from This query does not free the table space
memory. from memory.
Let’s look at some examples of the DROP and TRUNCATE statements in SQL and understand their
working:
Student Table
To create this table, write the following queries:
SQL
ROLL_NO INT,
NAME VARCHAR(25),
ADDRESS VARCHAR(25),
PHONE INT ,
(1,'Ram','Delhi',9415536635,24),
(2,'Ramesh','Gurgaon',9414576635,21),
(3,'Sujit','Delhi',9815532635,20),
(4,'Suresh','Noida',9115536695,21),
(5,'Kajal','Gurgaon',8915536735,28),
(6,'Garima','Rohtak',7015535635,23);
Query:
Query:
After running the above query whole table from the database will be deleted.
In this example, we will truncate the Student_details table from the student_data database.
Query:
Completely removes a table or database from the database, including the data and
structure.
Removes all the rows or data from a table, but preserves the table structure and columns.
Resets the identity column (if any) back to its seed value.
Conclusion
In SQL, both DROP and TRUNCATE commands are used for removing data, but their impacts are
different. DROP is used when you want to completely remove a table or database, while TRUNCATE is
more efficient for removing all rows from a table without affecting its structure. Understanding when
and how to use these commands will help you maintain better control over your database and
optimize your database management processes.
Relational databases play an important role in managing data, especially during complex
operations like updates and deletions. To maintain data integrity, it is essential to back up
tables before making changes. SQL backup tables ensure the safety of the original dataset, allow
for data recovery, and facilitate safe experimentation.
This article explains the importance of backup tables, demonstrates various methods for creating
them in MySQL, PostgreSQL, and SQL Server, and highlights the limitations of common approaches.
Backup tables are essential during complex data changes or migrations because they let us safely
restore the original data if something goes wrong. Here are the key reasons why creating them is
essential:
Data Integrity: Protecting the original dataset from accidental loss or corruption.
Disaster Recovery: Ensuring that the data can be restored in case of failure or errors during
modifications.
Safe Experimentation: Making changes to data without affecting the live dataset.
Data Migration: Moving data from one system or table to another without losing original
records.
We will be using the following table “Student Information” which consists of data of Geeks who
enrolled in our DSA course as shown below:
1 22 Harry Male
2 23 Vishal Male
3 20 Snehal Female
4 25 Ram Male
5 24 Hina Female
We can create a backup of a table by creating a duplicate or copy of original database. This is
particularly useful for preserving the original table before performing updates, deletions, or other
modifications. Below is a detailed explanation of the syntax and terms used for this operation.
Syntax
Key Terms
AS: Acts as an alias, enabling the SQL query to copy data from the source table into the
backup table.
In this example, we will create a backup table “stud_1” of “student_information” table by creating a
copy of “student_information” table that duplicates all columns and their data..
Query:
Output
SQL Backup Table with All Columns Data Example Output
In this example, we create a backup table, “stud_2”, by copying only selected columns from
the “student_information” table using a SELECT statement.
Query:
Output
Till now we have seen how to create a clone of the source table. In the above backup table, the
data is also copied along with the table. However, we can also create a backup table without copying
the data.
Query:
Output
SQL Backup Table with No Data Example Output
Query:
Output
SQL Backup Table with Specific Columns and No Data Example Output
While the CREATE TABLE AS SELECT statement is a convenient method for creating backup tables, it
has some limitations which are as follows:
Constraints Are Not Copied: Constraints such as PRIMARY KEY, FOREIGN KEY, UNIQUE,
CHECK, and DEFAULT are not carried over to the new table.
Indexes and Triggers Are Not Copied: Any indexes or triggers defined on the base table are
not included in the backup table.
Manual Effort Required for Full Duplication: To replicate the full structure of the original
table, including constraints and indexes, you must manually define these elements after
creating the table.
To copy the structure of a table along with its constraints, the CREATE TABLE AS SELECT statement is
not sufficient. Instead, we need to define the table structure manually and then copy the data.
Conclusion
Creating backup tables in SQL is an essential practice for ensuring data integrity, facilitating disaster
recovery, and enabling experimentation without compromising the original data. While the CREATE
TABLE AS SELECT statement is a quick and convenient method, it has limitations such as
the exclusion of constraints, indexes, and triggers. For a more complete backup, manual
intervention is required to replicate the full structure of the original table.
FAQs
To create a backup table in SQL, use the CREATE TABLE statement with a SELECT * query to copy the
contents of the original table into a new one:
CREATE TABLE backup_table AS SELECT * FROM original_table;
In SQL, creating a backup involves using the database management system’s specific tools, such as
mysqldump for MySQL, or pg_dump for PostgreSQL. These tools generate a dump file of the
database or table: mysqldump -u username -p database_name > backup.sql
To save a created table, simply use the CREATE TABLE statement to define its structure and data, then
execute the query. SQL databases automatically save the table when the statement is committed.
CREATE TABLE table_name (column1 datatype, column2 datatype,.);
A temporary table in SQL is a special type of table that is created and stored in the system’s
temporary database (such as TempDB in SQL Server). This table is primarily used to store and
generate important mediation results when executing a query, stored procedure, or session.
Temporary tables are automatically deleted when the session or transaction that created them ends,
making them perfect for temporary or intermediate data storage. They are particularly useful in
situations where you need to perform calculations or data transformations without changing the
permanent database structure.
Syntax:
Result:
id name
1 Lalit
2 Atharva
There are 2 types of Temporary Tables: Local Temporary Table, and Global Temporary Table. These
are explained as following below.
A Local Temp Table is available only for the session that has created it. It is automatically dropped
(deleted) when the connection that has created it, is closed. To create Local Temporary Table Single
“#” is used as the prefix of a table name. Also, the user can drop this temporary table by using
the “DROP TABLE #EmpDetails” query. There will be Random Numbers are appended to the Name of
Table Name. If the Temporary Table is created inside the stored procedure, it get dropped
automatically upon the completion of stored procedure execution.
Example:
BEGIN
END
EXECUTE ProcTemp
Global Temporary Table: To create a Global Temporary Table, add the “##” symbol before the table
name.
Example:
Global Temporary Tables are visible to all connections and Dropped when the last connection
referencing the table is closed. Global Table Name must have an Unique Table Name. There will be
no random Numbers suffixed at the end of the Table Name.
Conclusion
Temporary tables in SQL are powerful tools for managing central data, performing complex
calculations, and improving query performance. Whether you use local temporary tables for session-
specific operations or global temporary tables to share data across multiple sessions, understanding
how to use these tables effectively will inform your database management processes simplified
Temporary tables for storing and manipulating data without impacting the permanent database
structure provide options , which make them ideal for tasks such as data manipulation, backup and
testing.
The SQL ALTER TABLE statement is a powerful tool that allows you to modify the structure of an
existing table in a database. Whether you’re adding new columns, modifying existing ones, deleting
columns, or renaming them, the ALTER TABLE statement enables you to make changes without losing
the data stored in the table.
In this article will learn about the ALTER TABLE statement with examples to demonstrate how it
works.
The ALTER TABLE statement in SQL is used to add, remove, or modify columns in an existing table.
The ALTER TABLE statement is also used to add and remove various constraints on existing tables.
It allows for structural changes like adding new columns, modifying existing ones, deleting columns,
and renaming columns within a table.
Syntax:
Here, the clause is the operational clause of the ALTER TABLE statement. Some key clauses of the
ALTER TABLE statement are:
The ADD clause is used to add a new column to an existing table. You must specify the name of the
new column and its data type.
Query:
The MODIFY (or ALTER COLUMN in some databases like SQL Server) clause is used to modify the
definition of an existing column, such as changing its data type or size.
Query:
Query:
You can rename an existing column using the RENAME COLUMN clause. This allows you to change
the name of a column while preserving its data type and content.
Query:
You can rename an entire table using the RENAME TO clause. This changes the name of the table
while preserving its structure and data.
RENAME TO new_table_name;
Below are the examples of ALTER TABLE statement. These examples demonstrates different use cases
and shows how to use ALTER TABLE statement in SQL.
The following SQL query adds an “Email” column to the “Students” table:
The following query deletes the “Email” column from “Students” table:
1 Ram
2 Abhi
3 Rahul
4 Tanu
Query:
Output:
1 Ram
2 Abhi
3 Rahul
4 Tanu
Query:
After running the above query the maximum size of the Course Column is reduced to 20 from 40.
Output:
1 Ram
2 Abhi
3 Rahul
4 Tanu
Conclusion
The SQL ALTER TABLE statement is an essential tool for modifying the structure of an existing table.
Whether you need to add, delete, or modify columns, or even rename the table or columns, ALTER
TABLE provides the flexibility needed to manage your database schema efficiently. By following best
practices and using this command wisely, you can maintain the integrity and performance of your
database while making necessary structural changes.