Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

SQL (Structured Query Language) (3)

Uploaded by

gnumber019
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

SQL (Structured Query Language) (3)

Uploaded by

gnumber019
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 19

SQL (STRUCTURED

QUERY LANGUAGE)
SQL, or Structured Query Language, is a domain-specific language used for
managing and manipulating relational databases. It is a standard language for
interacting with databases and is commonly used in various database
management systems (DBMS) such as MySQL, PostgreSQL, Oracle, Microsoft
SQL Server, and SQLite, among others.
SQL allows you to perform various operations on a database, including:
Data Querying: Retrieve data from a database using the SELECT statement.
Data Manipulation: Add, update, or delete data in a database using INSERT,
UPDATE, and DELETE statements.
Data Definition: Define and modify the structure of a database, including
creating tables, altering table structures, and defining constraints using
statements like CREATE TABLE, ALTER TABLE, and CREATE INDEX.
Data Control: Manage user permissions and access control using statements
like GRANT and REVOKE.
SQL also provides data types that define the kind of data that can be stored in a
database. Common SQL data types include:
Numeric Types:
INT (Integer)
SMALLINT (Small Integer)
BIGINT (Big Integer)
DECIMAL or NUMERIC (Fixed-point numbers)
FLOAT (Floating-point number)
REAL (Single-precision floating-point)
DOUBLE PRECISION (Double-precision floating-point)
Character Strings:
CHAR (Fixed-length character string)
VARCHAR (Variable-length character string)
TEXT (Unlimited-length character string)
Date and Time Types:
DATE (Date without time)
TIME (Time without date)
TIMESTAMP (Date and time)
INTERVAL (Time intervals)
Boolean Type:
BOOLEAN (True/False)
Binary Data Types:
BINARY (Fixed-length binary data)
VARBINARY (Variable-length binary data)
BLOB (Binary Large Object for large binary data)
Other Data Types:
ENUM (Enumeration of values)
ARRAY (Array of values)
JSON (JSON data)
UUID (Universally Unique Identifier)
Custom Types: Some database systems allow you to define custom
data types based on your application's requirements.
CONSTRAINTS IN SQL
In SQL, constraints are rules or conditions applied to a table's columns to maintain the
integrity, accuracy, and consistency of the data in a database. Constraints are used
to define limits on what kind of data can be stored in a table. They help ensure that
data adheres to the desired structure and business rules. Common constraints in
SQL include:
Primary Key Constraint:
Ensures that each value in a column or a set of columns is unique.
Enforces data integrity by ensuring that each row can be uniquely identified.
A table can have only one primary key, and it can consist of one or multiple columns.
Example: PRIMARY KEY (employee_id)
Unique Constraint:
Ensures that each value in a column or a set of columns is unique.
Unlike a primary key, a table can have multiple unique constraints.
Example: UNIQUE (email)
Foreign Key Constraint:
Establishes a link between two tables, ensuring that the values in a column(s) of one table match
the values in a column(s) of another table.
Enforces referential integrity, preventing orphaned or inconsistent data.
Example: FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
Check Constraint:
Defines a condition that must be met for data to be inserted or updated in a column.
It can be used to restrict the range of valid values for a column.
Example: CHECK (age >= 18)
Default Constraint:
Assigns a default value to a column when no explicit value is provided during an
insert operation.
Example: DEFAULT 'N/A'
Not Null Constraint:
Requires that a column cannot contain NULL values.
Ensures that each row has a value for the constrained column.
Example: NOT NULL
Unique Key Constraint:
Similar to the unique constraint but allows multiple NULL values.
Ensures that non-NULL values are unique within the column.
Example: UNIQUE KEY (ssn)
Check Constraint with Function:
Allows more complex conditions using a user-defined function.
Example: CHECK (is_valid_date(order_date))
Inclusion Constraint:
Restricts a column to a predefined set of values.
Example: status IN ('Pending', 'Shipped', 'Delivered')
Constraints help maintain data quality, prevent data inconsistencies,
and improve database performance by reducing the likelihood of
errors.
 Step 1: Create a Table
 We'll start by creating a table called "Books" with the
following columns:
 BookID (Primary Key)
 Title
 Author
 PublicationYear
 Price
 Step 2: Insert Data
 Let's insert some sample data into the

"Books" table:
 Step 3: Select Data
 Now, let's retrieve information from the

"Books" table:
 Step 4: Update Data
 You can update existing data in the table.

For example, let's update the price of "The


Great Gatsby":
 Step 5: Delete Data
 To remove records from the table, you can use the
DELETE statement. Let's delete a book from the table:

 Step 6: Additional Operations


 You can perform additional operations such as sorting and
aggregation:
 Sort books by price in descending order:
 Calculate the average price of books:

UNIQUE KEY
 A unique key is a database constraint that ensures
that the values in a specified column or set of
columns are unique across all rows in a table. In
other words, it enforces that no two rows in the table
can have the same values in the unique key
column(s). This constraint is useful for ensuring data
integrity and preventing duplicate records.
 Here's how you can define a unique key in SQL with
an example:
 Example Table: "Students"
 Suppose you have a table called "Students"

with the following columns:


 StudentID (Primary Key)
 StudentName
 StudentEmail
 In this example:
 The StudentID column is the primary key, which uniquely
identifies each student.
 The StudentEmail column has a unique key constraint defined
using the UNIQUE keyword. This constraint ensures that no two
students can have the same email address. If you try to insert or
update a record with a duplicate email address, the database will
generate an error.
 Here's an example of how you might insert data into the
"Students" table while ensuring the uniqueness of email
addresses:
 The second INSERT statement will generate
an error because it attempts to insert a
student with the same email address as an
existing student, violating the unique key
constraint. This constraint helps maintain
data integrity and prevents duplicate email
addresses in the "Students" table.
FOREIGN KEY
 A foreign key is a field or a set of fields in one table that refers to
the primary key of another table. It establishes a relationship
between two tables and enforces referential integrity. Here's an
example of how to create a foreign key relationship between two
tables:
 Suppose you have two tables, "Customers" and "Orders," where
each order is associated with a customer. You can create a foreign
key in the "Orders" table that references the "Customers" table to
ensure that every order is related to a valid customer.
 Orders Table with a Foreign Key:

 In this example:
 In the "Customers" table, CustomerID is the primary key, which
uniquely identifies each customer.
 In the "Orders" table, there is a foreign key named CustomerID.
This foreign key establishes a relationship between the "Orders"
table and the "Customers" table.
 The FOREIGN KEY (CustomerID) REFERENCES
Customers(CustomerID) constraint specifies that the CustomerID
column in the "Orders" table references the CustomerID column
in the "Customers" table. It ensures that every value in the
"CustomerID" column of the "Orders" table corresponds to a valid
value in the "CustomerID" column of the "Customers" table.
 With this foreign key relationship, you can do things like:
 Insert new orders and associate them with existing customers
using valid CustomerID values.
 Prevent the insertion of orders with non-existent or incorrect
CustomerID values.
 Update or delete customer records while preserving the
integrity of associated order data.
 Foreign keys are a crucial part of maintaining data consistency
and integrity in a relational database by enforcing relationships
between tables.
To add data for orders of customers in the
example I provided, you can insert records into the
"Orders" table while ensuring that the CustomerID values
you use exist in the "Customers" table. Here's how you
can do it:
 Assuming you have already inserted customer records into
the "Customers" table, you can insert orders for those
customers as follows:
 In the above SQL statements:
 We use the INSERT INTO statement to add new
records to the "Orders" table.
 The CustomerID values (1 and 2 in this example)
correspond to existing customers in the
"Customers" table.
 The OrderDate and TotalAmount columns are
populated with relevant data for each order.
 You can insert more orders for different customers
by changing the CustomerID and other order details
accordingly.

You might also like