0% found this document useful (0 votes)
5 views

SQL NOTES

The document provides an overview of Structured Query Language (SQL), highlighting its role as a standard language for managing and manipulating data in relational databases. It covers SQL's capabilities, including data retrieval, modification, and database management, along with its syntax rules and various data types. Additionally, it details specific SQL commands and clauses, emphasizing their functions and usage in database operations.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

SQL NOTES

The document provides an overview of Structured Query Language (SQL), highlighting its role as a standard language for managing and manipulating data in relational databases. It covers SQL's capabilities, including data retrieval, modification, and database management, along with its syntax rules and various data types. Additionally, it details specific SQL commands and clauses, emphasizing their functions and usage in database operations.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

The database is becoming increasingly integrated, creating a clamor for standard

language that can work in different computing environments. SQL has proved to be
the standard language as it allows programmers or developers to learn one set of
commands and use them to create, retrieve, alter, and or transfer data regardless of
whether they are working on the PC, a workstation, a mini, or a mainframe. In this
tutorial, you will learn about the introduction of the structured query language. or
handling database and database-related programming, programmers need to have
some medium or interface to particularize a set of commands or codes to deal with a
database or access the database's data. SQL(Structured Query Language) is a
standard database programming language for accessing and manipulating data in a
relational database.

What Will You Get Learning SQL?

SQL gives unique learning and database handling techniques on Structured Query
language and will help you make better command over the SQL queries and to deal
with these codes efficiently. Since SQL helps you to include database creation,
database or table deletion, fetching row data and modifying those data, etc., in
parallel, SQL makes things automatic and smooth for end-users to access and deal
with that application's data efficiently.

SQL (Structured Query Language) is a computer-based structured, formatted


database language designed for managing data in Relational Database
Management Systems (RDBMS). SQL is a standardized computer language that
was initially developed by IBM for querying, altering, and defining relational
databases using declarative statements.

 IBM initially developed SQL in the 1970s.


 SQL is pronounced as "sequel".
 SQL is a computer language for storing, manipulating, and retrieving data in a
relational database.
 SQL allows you to create, modify and query databases.
 SQL is a standard language that is used by most relational databases.
 SQL is used to access and manipulate data stored in tables.
 SQL is used to join multiple tables, create views, stored procedures, and
triggers.
 SQL is used to create and manage the schema of the database.
 SQL can be used to control access to the data and manage the transaction.
 SQL is used to create reports and data visualizations.
 SQL is used for data validation and data integrity.
 SQL is used for data security and backup, and recovery.
 SQL is used for performance tuning and optimization.
 SQL is used for troubleshooting and monitoring the database performance.

What Can SQL Do?

SQL (Structured Query Language) can perform a wide range of operations on a


relational database. Some of the main things that SQL can do include:
 SELECT: Retrieve specific data from one or more tables.
 INSERT: Add new data to a table.
 UPDATE: Modify existing data in a table.
 DELETE: Remove data from a table.
 CREATE: Create new tables, views, stored procedures, and other database
objects.
 ALTER: Modify the structure of existing tables, views, and other database
objects.
 DROP: Remove tables, views, and other database objects.
 INDEX: Create and manage indexes to improve the performance of queries.
 JOIN: Retrieve data from multiple tables based on a related column.
 UNION: Combine the results of various SELECT statements.
 GROUP BY: Group data by one or more columns and perform aggregate
functions.
 HAVING: Filter data based on aggregate functions.
 WHERE: Filter data based on specific conditions.
 ORDER BY: Sort data in ascending or descending order.
 LIMIT: Retrieve a particular number of rows from the result set.
 TRUNCATE: Remove all data from a table, but keep the table structure.

These are just a few examples of the many operations that can be performed using
SQL, and the specific set of commands and functionality may vary depending on the
specific relational database management system (RDBMS) being used.

QL syntax refers to the rules and guidelines defining how to correctly write SQL
statements. It includes the use of keywords, clauses, operators, and functions that
are used to query and manipulate data in a relational database.

The basic syntax of an SQL statement consists of a command followed by a clause


and conditions. The most common SQL commands are SELECT, INSERT,
UPDATE, DELETE, and CREATE. Each command has its specific syntax and
performs a particular task.

SQL Clause
In SQL (Structured Query Language), a clause is a component of a SQL statement
that performs a specific function. For example, the SELECT clause specifies the
columns to be retrieved, the WHERE clause specifies a condition to filter rows, and
the ORDER BY clause sorts the result set.

On the other hand, an SQL statement is composed of several clauses, each with a
specific purpose and syntax. It is a complete command that is executed against a
database. An SQL statement can contain one or more clauses, depending on the
task performed. For example, a SELECT statement typically includes a SELECT
clause, a FROM clause, and possibly others such as WHERE, GROUP BY,
HAVING, and ORDER BY.
Some standard SQL clauses include:

SELECT Clause

The SELECT clause in SQL is used to specify the columns in a SELECT statement.
It is used to query a database and retrieve specific data from one or more tables in
the database. The syntax for the SELECT clause is as follows:

SELECT column, column1, ...


FROM table_name

WHERE clause

The WHERE clause in SQL filters the rows returned by a SELECT, UPDATE, or
DELETE statement. The WHERE clause is used to specify a condition that must be
true for a row to be included in the result set or affected by the statement. The basic
syntax of a WHERE clause is:

Syntax:

Copy CodeSELECT column, column1, ...


FROM table_name
WHERE condition;

AND/OR CLAUSE

The SQL AND and OR operators are used in the WHERE clause to combine multiple
conditions in a query. The AND operator returns rows that satisfy both conditions,
while the OR returns rows that satisfy either. The basic syntax of a WHERE clause
with AND and OR operators is:

Syntax:

Copy CodeSELECT column, column1, ...


FROM table_name
WHERE condition AND/OR condition1 AND/OR ...;

ORDER BY Clause

The SELECT statement in SQL is used to retrieve data from one or more tables in a
database. The ORDER BY clause is used to sort the result set by one or more
columns. The basic syntax of a SELECT statement with an ORDER BY clause is:

Syntax:

Copy CodeSELECT column, column1, ...


FROM table_name
ORDER BY column [ASC | DESC], column1 [ASC | DESC], ...;
INSERT INTO Clause
The INSERT INTO clause in SQL adds new rows of data to a table. The basic syntax
of the INSERT INTO clause is:

Syntax:

Copy CodeINSERT INTO table_name (column, column1, ...)


VALUES (value, value1, ...);

UPDATE Clause

The UPDATE clause in SQL is used to modify existing data in a table. It is typically
used in conjunction with a SET clause to specify the new values for the columns and
a WHERE clause to identify the rows that should be updated. The basic syntax of
the UPDATE clause is:

Syntax:

Copy CodeUPDATE table_name


SET column = value, column1 = value1, ...
WHERE condition;
DELETE Clause

The DELETE clause in SQL is used to delete existing rows of data from a table. It is
typically used in conjunction with a WHERE clause to specify the rows that should be
deleted. The basic syntax of the DELETE clause is:

Syntax:

Copy CodeDELETE FROM table_name


WHERE condition;

SQL SYNTAX RULES

SQL syntax has a set of rules that must be followed for a SQL statement to be valid.
Here are some of the most important rules to keep in mind when writing SQL
statements:

1. SQL statements always start with the keywords.


2. SQL keywords must be written in uppercase. For example, SELECT, FROM,
WHERE, etc.
3. SQL statements must end with a semicolon (;).
4. Table and column names must be written in lowercase; if multiple words are
used, they should be separated by an underscore (_) or camelCase.
5. String values must be enclosed in single quotes (' ').
6. Date values must be enclosed in single quotes (' ') and should be in the
format 'YYYY-MM-DD'.
7. Numeric values should not be enclosed in quotes.
8. Each clause in a SQL statement should be written on a separate line for
better readability.
9. The SELECT clause must come first in a SELECT statement, followed by the
FROM clause and other clauses such as WHERE, JOIN, GROUP BY, and
ORDER BY.
10. When using the WHERE clause to filter results, the comparison operator must
be placed between the column name and the value being compared.

SQL data types


SQL data types specify the type of data that a column or variable can hold in a SQL
database. These data types include numeric, character and string, date and time,
binary, boolean, enumerated, array, and JSON types. Each data type has a specific
range of values and uses. Choosing the appropriate data type for a column or
variable is essential for accurate and efficient data storage and retrieval.

SQL data types can be broadly categorized into several categories:

1. Numeric data types: It stores numeric values, such as integers and floating-
point numbers. Examples include INT, BIGINT, FLOAT, NUMERIC, and DECIMAL.
2. Character and string data types: It stores character strings, such as names
and addresses. Examples include CHAR, VARCHAR, and TEXT.
3. Date and time data types: It stores date and time values. Examples
include DATE, TIME, DATETIME, and TIMESTAMP.
4. Binary data types: It stores binary data, such as images and files. Examples
include BLOB, BINARY, and VARBINARY.
5. Boolean data types: It stores true/false values. Examples
include BOOL and BOOLEAN.
6. Enumerated data types: It stores a predefined set of values. Examples
include ENUM.
7. Array data types: It stores multiple values of the same data type. Examples
include ARRAY.
8. JSON data types: It stores JSON data. Examples include JSON and JSONB.

Here are some examples of common SQL data types and their uses:

Data Type Description


INT The INT data type stores integer values. It can hold whole numbers, such
as items in stock or orders placed. INT values can range from -
2147483648 to 2147483647.
BIGINT The BIGINT data type stores large integers. It can be used to hold whole
numbers larger than the range of values that can be stored in the INT data
type. BIGINT values can range from -9223372036854775808 to
9223372036854775807.
SMALLINT The SMALLINT data type stores smaller integers. It can be used to hold
whole numbers smaller than the range of values that can be stored in
the INT data type. SMALLINT values can range from -32768 to 32767.
TINYINT The TINYINT data type stores very small integers. It can be used to hold
whole numbers smaller than the range of values that can be stored in
the SMALLINT data type. TINYINT values can range from 0 to 255.
NUMERIC The NUMERIC data type stores exact numeric values with a fixed precision
and scale. The precision is the total number of digits in a number, and the
scale is the number of digits to the right of the decimal point. For example,
124.56 has a precision of 5 and a scale of 2.
DECIMAL The DECIMAL data type is similar to the NUMERIC data type that stores
exact numeric values with a fixed precision and scale. It's important to
note that NUMERIC and DECIMAL are synonyms in SQL, and it's up to the
developer to choose which one to use.
FLOAT The FLOAT data type stores approximate numeric values with a floating-
point representation. It can store very large or tiny numbers with many
digits before and after the decimal point.
REAL The REAL data type stores approximate numeric values with a floating-
point representation. It is similar to the FLOAT data type but uses fewer bits
to represent the value, meaning it has a smaller range and less precision.
DOUBLE The DOUBLE PRECISION data type stores approximate numeric values with
PRECISION a floating-point representation, similar to the FLOAT and REAL data
types. DOUBLE PRECISION is often used to store floating-point numbers with
higher precision than the FLOAT data type.
CHAR The CHAR data type stores fixed-length character strings. It can hold a
fixed number of characters, specified by the field's length. For example,
a CHAR(10) field can store a string of up to 10 characters. If the inserted
string is shorter than the specified length, the remaining characters will be
filled with spaces.
VARCHAR The VARCHAR data type stores variable-length character strings. It can
hold a variable number of characters, specified by the field's length. For
example, a VARCHAR(10) field can store a string of up to 10 characters. If
the string inserted is shorter than the specified length, it will only use the
necessary amount of storage.
TEXT The TEXT data type stores variable-length character strings, similar to
the VARCHAR data type. It can store a large amount of character data, and
the maximum length of a TEXT field is typically much larger than that of
a VARCHAR field. The exact maximum length of a TEXT field can vary
depending on the specific SQL implementation being used.
DATE The DATE data type stores date values. It can be used to hold a date,
which includes the day, month, and year. It's defined as DATE and used to
store date information such as birthdate, hiring date, order date, etc. The
format of a DATE value can vary depending on the specific SQL
implementation being used, but it typically follows the format of "YYYY-
MM-DD" where YYYY represents the year, MM represents the month, and
DD represents the day.
TIME The TIME data type stores time values. It can keep time, which includes
hours, minutes, and seconds. It can store information such as opening,
closing, arrival, departure, etc. The format of a TIME value can vary
depending on the specific SQL implementation being used, but it typically
follows the format of "HH:MM:SS" where HH represents the hour, MM
represents the minutes, and SS represents the seconds.
DATETIME The DATETIME data type stores both date and time values. It can be used
to hold a date and time, which includes the day, month, year, and time,
which consists of the hours, minutes, and seconds. It's defined
as DATETIME, and it's used to store date and time information such as start
time, end time, and timestamp. The format of a DATETIME value can vary
depending on the specific SQL implementation, but it typically follows the
format of "YYYY-MM-DD HH:MM:SS".
TIMESTAMP In SQL, the TIMESTAMP data type stores both date and time values, similar
to the DATETIME data type. It can be used to store a date, which includes
the day, month, year, and time, which consists of the hours, minutes, and
seconds. It's defined as TIMESTAMP, which stores date and time
information such as start time, end time, and timestamp. The format of
a TIMESTAMP value can vary depending on the specific SQL
implementation being used. Some implementations provide automatic
initialization and updating for TIMESTAMP columns.
YEAR The YEAR data type stores year values. It can be used to hold a year,
which includes four digits representing the year. It's defined as YEAR and
used to store year information such as birth year, hire year, etc.
BINARY The BINARY data type stores fixed-length binary data. It is comparable to
the CHAR data type but holds binary values instead of character strings.
The BINARY data type requires a fixed length to be specified and can be
used to store any binary data, such as images, audio, or other binary files.
VARBINARY The VARBINARY data type stores variable-length binary data. It is similar to
the VARCHAR data type but holds binary values instead of character
strings. The VARBINARY data type requires a maximum length to be
specified and can be used to hold any binary data, such as images, audio,
or other binary files.
BLOB The BLOB (Binary Large OBject) data type stores extensive binary data
such as images, audio, or other binary files. It can hold a large amount of
binary data, and the maximum size of a BLOB field can vary depending on
the specific SQL implementation being used. BLOB is typically used to
store data that is not character or string data.
BOOLEAN The BOOLEAN data type stores true/false or yes/no values. It can hold only
two possible values: TRUE, FALSE, YES, or NO. It's defined as BOOLEAN and
used to store logical values. The exact representation of a BOOLEAN value
can vary depending on the specific SQL implementation being used, but it
typically follows the format of "TRUE" or "FALSE" or "1" or "0" or "YES" or
"NO".
ENUM The ENUM data type stores a predefined set of values. It is a string object
with a value chosen from a list of permitted values specified when the
table is created. It is similar to a string object but is more restrictive in that
it only allows values included in the list of permitted values.
ARRAY The ARRAY data type stores an ordered collection of elements. It is a
variable-size multidimensional array and can hold a list of values with the
same data type. The elements of an array can be any data type, such as
integers, strings, or other complex data types. The size of an array is not
fixed and can be changed dynamically.
JSON The JSON data type stores JSON (JavaScript Object Notation) data. It is a
lightweight data-interchange format that is simple for humans to read and
write and for machines to parse and generate.
JSONB The JSONB data type stores binary representation of JSON (JavaScript
Object Notation) data. JSONB (binary JSON) is an optimized binary format
of JSON data. It is similar to the JSON data type but stores the data in a
binary format, making it more efficient in terms of storage and
retrieval. JSONB also provides additional functionality, such as indexing and
searching capabilities on the JSON data.
UUID The UUID (Universally Unique Identifier) data type stores unique identifier
values. It is a 128-bit value represented as a hexadecimal string, usually in
the format of "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX". It is
designed to have a very low probability of the same value being generated
twice, hence the term "universally unique".
IP The IP ADDRESS data type stores Internet Protocol (IP) address values. It
ADDRESS is a string representation of an IP address, usually in the format of
"xxx.xxx.xxx.xxx" for IPv4 addresses and
"xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx" for IPv6 addresses.
CIDR The CIDR (Classless Inter-Domain Routing) data type stores IP network
addresses in a compact representation. It is a string representation of an
IP network address, usually in the format of "xxx.xxx.xxx.xxx/yy" for IPv4
addresses and "xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/yy" for IPv6
addresses. The "yy" represents the number of bits of the IP address used
to identify the network, also called the prefix length.

DATABASE CONCEPT

A database intends to have a collection of data stored together to serve as multiple


applications as possible. Hence a database is often conceived of as a repository of
information needed for running certain functions in a corporation or organization.
Such a database would permit not only the retrieval of data but also the continuous
modification of data needed for the control of operations. It may be possible to
search the database to obtain answers to queries or information for planning
purposes.

Purpose of Database
A database should be a repository of data needed for an organization's data
processing. That data should be accurate, private, and protected from damage. It
should be accurate so that diverse applications with different data requirements can
employ the data. Different application programmers and various end-users have
different views upon data, which must be derived from a common overall data
structure. Their methods of searching and accessing data will be different.

Advantages of Using Database


 Database minimizes data redundancy to a great extent.
 The database can control the inconsistency of data to a large extent.
 Sharing of data is also possible using the database.
 Database enforce standards.
 The use of Databases can ensure data security.
 Integrity can be managed using the database.

Various Levels of Database Implementation


The database is implemented through three general levels. These levels are:

 Internal Level or Physical level


 Conceptual Level
 External Level or View Level

The Concept of Data Independence


As the database may be viewed through three levels of abstraction, any change at
any level can affect other levels' schemas. Since the database keeps on growing,
then there may be frequent changes at times. This should not lead to redesigning
and re-implementation of the database. The concepts of data independence prove
beneficial in such types of contexts.

 Physical data independence


 Logical data independence

Basic Terminologies Related to Database and SQL


Relation: In general, a relation is a table, i.e., data is arranged in rows and columns.
A relation has the following properties:

 In any given column of a table, all the items are of the same kind, whereas
items in different columns may not be of the same kind.
 For a row, each column must have an atomic value, and also, for a row, a
column cannot have more than one value.
 All rows of a relation are distinct.
 The ordering of rows in a relationship is immaterial.
 The column of a relation are assigned distinct names, and the ordering of
these columns is immaterial.

Tuple: The rows of tables in a relationship are generally termed Tuples.

Attributes: The columns or fields of a table are termed Attributes.

Degree: The number of attributes in a relation determines the degree of the relation.
A relation having three attributes is said to have a relation of degree 3.

Cardinality: The number of tuples or rows in a relation is termed cardinality.


The various processing capabilities of SQL are:

Type Description
Data Definition Language (DDL) The SQL DDL offers commands for defining
relation schemas, deleting relations, creating
indexes, and modifying relation schemas.
Interactive data manipulation language DML includes query languages based on both
relational algebra and tuple relational calculus.
Embedded Data Manipulation The embedded form of SQL is designed for use
Language within general-purpose programs such as PL/1,
COBOL, Fortran, Pascal, or C.
View Definition The SQL DDL also includes commands for
defining views.
Authorization The SQL DDL includes commands for specifying
access rights to relations and views.
Integrity SQL provides some limited forms of integrity
checking. Future products and standards of SQL
will likely comprise enhanced features for integrity
checking.
Transaction Control SQL also includes commands for specifying the
beginning and end of transactions and commands
for controlling transaction processing.
Data Definition Language (DDL)

The database schema is specified by a set of definitions expressed by a particular


language called data definition language. Changes to the structure of a database are
handled by a different set of SQL statements, collectively termed as SQL Data
Definition Language, or DDL.

Using DDL statements, you can do the following:

 Define and create a new table.


 Remove a table that is no longer needed.
 Alter the definition of an existing table.
 Classify a virtual table (view) of data.
 Establish security controls for a database.
 Index creation to make table search faster.
 Control the physical storage of data by the DBMS.

DDL is also used to define the length of data items. It may also specify the encoding
the program uses in the data items (binary, character, bits, string, etc.).

Although the DDL and DML are two distinct parts of the SQL language, in most SQL-
based DBMS products, the split is a conceptual one only. Usually, the DDL and DML
statements are submitted to the DBMS in the same way, and they can be freely
intermixed in both interactive SQL sessions and programmatic SQL applications. If a
program or user needs a table to store its temporary results, it can create the table,
populate it, manipulate the data, and then delete it. Again, this is a significant
advantage over earlier data models, in which the database structure was fixed when
the database was created.

Data Manipulation Language (DML)

After the database schema has been specified and the database has been created,
the data can be manipulated using a set of procedures that are expressed by a
particular language called a data manipulation language.

By data manipulation, language means:

 Retrieval of information stored in the database.


 Insertion of new information into the database.
 Deletion of information from the database.
 Modification of data in the database.
 SQL CREATE DATABASE is a command that creates a new database in
RDBMS, such as MySQL, SQL Server, Oracle, and others. The statement
creates an empty database with the user's specified name.

The basic syntax for creating a new database using SQL is:
Syntax

Copy CodeCREATE DATABASE database_name;

For example, to create a new database named "mydb", you would use the
following SQL statement:

Example:
Copy CodeCREATE DATABASE mydb;

When the above statement is executed, a new database with the specified
name is created. The new database will be empty and contain no tables. You
can then use other SQL statements to create tables, insert data, and perform
different operations on the new database.

SQL ALTER DATABASE is an essential statement to modify the properties of an


existing database in a Relational Database Management System (RDBMS). This
statement is helpful if you want to rename a database, change its composition, or
modify file properties.

Basic Syntax
The basic syntax for the ALTER DATABASE statement is as follows:
Basic Syntax:

Copy CodeALTER DATABASE database_name [MODIFY <option> ...]


Here, database_name specifies the database you wish to alter, and <option> is a
keyword indicating the type of modification.

Common Options in ALTER DATABASE


The following are some of the most common options that can be used with the ALTER
DATABASE statement:

Renaming a Database

One of the most common uses of the ALTER DATABASE statement is to change the
name of a database. The MODIFY NAME clause lets you easily change the database
name. For example, to rename a database from "old_db" to "new_db":

Copy CodeALTER DATABASE old_db MODIFY NAME = new_db;

Modify Database Files

To change the properties of a database file, use the MODIFY FILE option:

Copy CodeMODIFY FILE (name = 'file_name', size = <size>, FILE_ACCESS =


<access>);

The name specifies the name of the file, the size sets the size of the file in bytes, and
the FILE_ACCESS determines the access mode for the file (READ_ONLY,
READ_WRITE, or WRITE_ONLY). For example, to resize a file named "old_file" to
10MB, use the following statement:

Copy CodeALTER DATABASE database_name MODIFY FILE (name = 'old_file', size =


10);

Control User Access

Another common use for the ALTER DATABASE statement is setting a database to
single-user or restricted-user mode. You can accomplish this by using the SET
clause with the SINGLE_USER or RESTRICTED_USER option. Setting a database to
single-user mode limits access to one user at a time, while restricted-user mode
allows only members of db_owner or sysadmin roles. For example, to set a database
named "mydb" to single-user mode, use the following statement:

Copy CodeALTER DATABASE mydb SET SINGLE_USER;


To set a database named "mydb" to restricted-user mode, use the following
statement:

Copy CodeALTER DATABASE mydb SET RESTRICTED_USER;

Change Database Collation

Using the COLLATE clause, you can also change the default collation of a database
with the ALTER DATABASE statement. Collation sets the rules for sorting and
comparing characters. For example, to change the collation of a database named
"mydb" to "utf8mb3_unicode_ci", use the following statement:

Copy CodeALTER DATABASE mydb COLLATE utf8mb3_unicode_ci;

Modify Recovery Model

You can change the recovery model of a database with the ALTER
DATABASE statement. The recovery model sets the database's strategy for
recovering data in the event of a failure. The most commonly used recovery models
are "FULL" and "SIMPLE". The full recovery model maintains a complete set of
transaction logs, providing the most comprehensive data recovery. In contrast, the
simple recovery model keeps only the most recent transaction logs, providing less
comprehensive data recovery. To change the recovery model of a database named
"mydb" to "Simple," use the following statement:

Copy CodeALTER DATABASE mydb SET RECOVERY SIMPLE;

Conclusion
The ALTER DATABASE statement is a powerful tool for modifying the properties of an
existing database. By understanding its basic syntax and some of the most common
options, you are well-equipped to manage your databases effectively.

This tutorial provides an overview of the most commonly used SQL commands to
create, alter, and manipulate tables and data in databases.

What Are SQL Commands?


SQL commands are standardized instructions used in Structured Query Language
(SQL) to communicate with a relational database management system (RDBMS)
and perform various tasks such as data manipulation, definition, and control. These
commands allow you to create, modify, delete, and retrieve data from database
tables and perform other database management operations.

Essential SQL Commands


Various SQL commands are available for managing databases, but some are
essential and commonly used:

SQL Command Description


CREATE DATABASE Initializes a new database.
CREATE TABLE Constructs a new table within a database.
ALTER DATABASE Alters the properties of an existing database.
ALTER TABLE Modifies the structure of an existing table.
DROP TABLE Removes a table and all its data.
INSERT INTO Adds new records to a table.
SELECT Fetches specific data from one or more tables.
UPDATE Alters existing records in a table.
DELETE Removes specified data from a table.
SQL Command Execution Order
Understanding the sequence in which SQL commands are executed is crucial. Begin
by creating a database, followed by tables within that database. Once your tables
are set up, you can manipulate data by inserting, updating, or deleting. Finally, use
the SELECT command to query and retrieve the data you need.

SQL CREATE TABLE is a command that creates a new table in the RDBMS
database, such as MySQL, SQL Server, Oracle, etc.

The syntax for creating a new table using SQL is:

Syntax:

Copy CodeCREATE TABLE table_name


(
column1 datatype constraint,
column2 datatype constraint,
...
column_n datatype constraint
);
When this statement is executed, a new table with the specified name is created.
The new table will have the columns and data types defined in the statement. It is
also possible to add constraints such as NOT NULL, UNIQUE, PRIMARY KEY,
FOREIGN KEY, and default value.
For example, in MySQL, the following SQL statement creates a new table named
"tbl_employee" in the database:

Example:

Copy CodeCREATE TABLE `tbl_employee` (


`employee_id` INT NOT NULL AUTO_INCREMENT,
`last_name` VARCHAR (100) NOT NULL,
`first_name` VARCHAR (100) NOT NULL,
`address` VARCHAR (255),
PRIMARY KEY (`employee_id`)
) ENGINE = INNODB CHARSET = utf8 COLLATE = utf8_unicode_ci;

Learn how the ALTER TABLE statement in SQL streamlines your database
management by simplifying modifications to a table's structure without affecting its
data. This feature allows easy modification of table columns, constraints, and
indexes.

Why Use ALTER TABLE?


When you need to change your database table, such as to accommodate new data
types or business requirements, you can use ALTER TABLE to seamlessly modify
tables rather than recreating them from scratch.

Syntax
The basic syntax for SQL ALTER TABLE is as follows:

Copy CodeALTER TABLE table_name


ADD column_name data_type [column_constraint],
MODIFY column_name data_type [column_constraint],
DROP column_name;
Here, The table_name is the name of the table you want to modify. You can use
the ADD keyword to add a new column to the table, the MODIFY keyword to modify an
existing column, and the DROP keyword to delete a column. The column_name is the
column name you want to add, modify, or delete. The data_type is the column's data
type, and the column_constraint is any constraint you wish to apply to the column.

How to Add a New Column


To add a new column to an existing table, use the following syntax:

Copy CodeALTER TABLE table_name


ADD column_name data_type [column_constraint];
For example, to add a new column named email of data type VARCHAR(50) to
the students table, you would use the following statement:

Copy CodeALTER TABLE students


ADD email VARCHAR(50);
Modify an Existing Column
To modify an existing column in an existing table, use the following syntax:

Copy CodeALTER TABLE table_name


ALTER column_name data_type [column_constraint];
For example, to modify the data type of the salary column in the employees table
from INTEGER to DECIMAL, you would use the following statement:

Copy CodeALTER TABLE employees


ALTER COLUMN salary DECIMAL;
Please note that ALTER is used in SQL Server and MS Access, while MODIFY
COLUMN is used in MySQL and Oracle.

How to Delete a Column


To delete a column from an existing table, use the following syntax:

Copy CodeALTER TABLE table_name


DROP COLUMN column_name;
For example, to delete the price column from the orders table, you would use the
following statement:

Copy CodeALTER TABLE orders


DROP COLUMN price;
Renaming a Table or Column
To rename a table or column, use the following syntax:

Copy CodeALTER TABLE old_table_name


RENAME TO new_table_name;
Copy CodeALTER TABLE table_name
RENAME COLUMN old_column_name TO new_column_name;
For example, to rename the employees table to staff and the age column to years,
you would use the following statements:

Copy CodeALTER TABLE employees


RENAME TO staff;

ALTER TABLE staff


RENAME COLUMN age TO years;
Adding Constraints
Tables can have constraints to enforce rules on data. For example, a unique
constraint ensures that no two rows in a table have the same value in a particular
column.

To add a constraint to a table, use the following syntax:

Copy CodeALTER TABLE table_name


ADD CONSTRAINT constraint_name constraint_definition;
For example, to add a unique constraint on the email column in the employees table,
you would use the following statement:

Copy CodeALTER TABLE employees


ADD CONSTRAINT UNIQUE_EMAIL UNIQUE (email);
Dropping Constraints
To drop a constraint from a table, use the following syntax:

Copy CodeALTER TABLE table_name


DROP CONSTRAINT constraint_name;
For example, to drop the UNIQUE_EMAIL constraint that we just added, you would use
the following statement:

Copy CodeALTER TABLE employees


DROP CONSTRAINT UNIQUE_EMAIL;
Conclusion
You've now grasped the essentials of using SQL's ALTER TABLE statement to
manage database tables effectively. Whether you're adding new columns or
enforcing data integrity through constraints, ALTER TABLE has got you covered.

You can use the DROP TABLE statement to delete a table from a database
permanently. This statement can be helpful if you no longer need the table's data or
want to begin fresh. This tutorial will guide you through how to use the DROP
TABLE statement, including its syntax and options.

What is the DROP TABLE Statement?


The DROP TABLE statement permanently deletes a table from a database, including
the table definition, all data stored in the table, and all associated indexes, triggers,
constraints, and permissions.

Basic DROP TABLE


Syntax:

The basic syntax of the DROP TABLE statement is as follows:

Copy CodeDROP TABLE table_name;


Example:

The following SQL statements drop the tables tbl_logs and tbl_tmp:

Copy CodeDROP TABLE tbl_logs;


DROP TABLE tbl_tmp;
DROP TABLE Options
Syntax:

Copy CodeDROP TABLE [IF EXISTS] [CASCADE | RESTRICT] table_name;


The DROP TABLE statement has the following options:

Option Description
IF EXISTSIt checks table existence to prevent errors.
CASCADE It drops the table along with dependent objects, such as views, triggers, and stored procedures.
RESTRICT It prevents table deletion if dependent objects exist.
DROP TABLE with IF EXISTS

Before attempting to delete a table, use IF EXISTS to check if it exists first to prevent
errors.

Example:

Copy CodeDROP TABLE IF EXISTS tbl_logs;


DROP TABLE with CASCADE

The CASCADE option with the DROP TABLE statement will also drop any associated
objects like stored procedures, triggers, and views. This option can be helpful when
you want to delete the table and all its related objects.

Example:

Copy CodeDROP TABLE tbl_logs CASCADE;


DROP TABLE with RESTRICT

The RESTRICT option prevents the DROP TABLE statement from dropping a table if any
dependent objects exist. This option is helpful if you are unsure whether there are
any dependent objects or do not want to delete them.

Example:

Copy CodeDROP TABLE tbl_logs RESTRICT;


Conclusion
The DROP TABLE statement in SQL allows you to delete an existing table from the
database. This statement can help manage the database by deleting unnecessary or
outdated tables. However, it is critical to use it with caution to avoid accidentally
deleting important data.

You might also like