A table in SQL is a collection of data organized in rows and columns. Each row represents a record, and each column represents an attribute or field of the record. SQL tables are used to store structured data in relational databases, where each table represents a specific entity (e.g., customers, orders, products).
Tables are the fundamental storage objects in a relational database. A well-designed table helps maintain data integrity and optimizes database performance.
You can create a table in SQL using the CREATE TABLE
statement. Here’s an example:
CREATE TABLE Customers (
CustomerID int,
FirstName varchar(50),
LastName varchar(50),
Email varchar(100),
Phone varchar(20),
PRIMARY KEY (CustomerID)
);
This statement creates a table called Customers
with columns for CustomerID
, FirstName
, LastName
, Email
, and Phone
. The CustomerID
is defined as the primary key, which uniquely identifies each customer.
Constraints in SQL are rules applied to columns in a table to ensure data accuracy and integrity. Here are some common constraints used in SQL tables:
Once a table is created, you can insert data into it using the INSERT INTO
statement. Here’s an example:
INSERT INTO Customers (CustomerID, FirstName, LastName, Email, Phone)
VALUES (1, 'Arshiya', 'Naaz', 'Arshiya.Naaz@example.com', '555-1234');
This statement adds a new record to the Customers
table with the values for CustomerID
, FirstName
, LastName
, Email
, and Phone
.
To retrieve data from a table, you can use the SELECT
statement. Here’s an example that retrieves all the data from the Customers
table:
SELECT * FROM Customers;
This query selects all columns from the Customers
table. You can also specify which columns to retrieve:
SELECT FirstName, LastName, Email FROM Customers;
To update existing data in a table, you can use the UPDATE
statement. Here’s an example:
UPDATE Customers
SET Email = 'MohammadMaaz@gmail.com'
WHERE CustomerID = 1;
This statement updates the email address for the customer with a CustomerID
of 1.
To delete data from a table, use the DELETE
statement. Here’s an example:
DELETE FROM Customers
WHERE CustomerID = 1;
This statement deletes the record where the CustomerID
is 1 from the Customers
table.