SQL Practice
SQL Practice
SQL Practice
• CHAR(n):
o Fixed-length string. Always stores exactly n characters, padding with spaces if necessary.
o Example: CHAR(10) will always store 10 characters (even if fewer characters are provided).
• VARCHAR(n):
o Variable-length string. Can store up to n characters but only uses the space required for the
actual string length.
o Example: VARCHAR(255) can store up to 255 characters but won’t use extra space for
shorter strings.
• TEXT:
o Used to store large amounts of text (e.g., articles, descriptions, etc.).
o The length can be much larger than VARCHAR, often limited by the system, but no length
specification is needed.
• DATE:
o Stores a date in the format YYYY-MM-DD.
o Example: 2024-11-05.
• TIME:
o Stores time in the format HH:MM:SS (hours, minutes, seconds).
o Example: 14:30:00.
• DATETIME (or TIMESTAMP):
o Stores both date and time in the format YYYY-MM-DD HH:MM:SS.
o Example: 2024-11-05 14:30:00.
• TIMESTAMP:
o Similar to DATETIME, but in some systems, this type might be used to automatically store
the time when a record is created or modified.
o Often includes time zone information.
• YEAR:
o Stores a year in a 4-digit format (YYYY), often used in year-based data like birthdates.
• BINARY(n):
o Stores fixed-length binary data, like images or other binary files.
o Example: BINARY(16) would store 16 bytes of binary data.
• VARBINARY(n):
o Stores variable-length binary data, similar to VARCHAR but for binary data.
o Example: VARBINARY(255) stores up to 255 bytes of binary data.
• BLOB (Binary Large Object):
o Used for storing large binary data (e.g., images, audio files).
o No length restriction in most systems, just limited by system resources.
• JSON:
o Stores JSON (JavaScript Object Notation) formatted data.
o This type is commonly used for NoSQL-like flexibility in SQL databases (supported in MySQL,
PostgreSQL, SQL Server, etc.).
o You can store complex objects and arrays directly.
• XML:
o Used to store XML (eXtensible Markup Language) formatted data.
o Some databases provide specific functions to query and manipulate XML data.
• ENUM:
o A string object with a predefined set of values.
o Example: ENUM('small', 'medium', 'large') would allow only one of these values.
• SET:
o A type for storing multiple values from a predefined list. Typically used to store a set of flags
or options.
• ARRAY (PostgreSQL):
o Allows you to store an array of values (e.g., INTEGER[] to store a list of integers).
• GEOMETRY / POINT, LINESTRING, POLYGON (PostgreSQL, MySQL Spatial Extensions):
o Used for storing spatial data such as coordinates and shapes.
o Can store points, lines, and polygons for geographic applications.
• MONEY:
o A type used for monetary values in some systems (e.g., SQL Server, PostgreSQL).
o Stores values in a fixed-point format with a specific precision.
Notes:
• Always check your specific DBMS documentation, as there can be slight differences in data type
implementations.
• Some data types are more suited for particular applications (e.g., DECIMAL for financial data, TEXT
for long descriptions, DATE for dates).
Comments in SQL
In SQL, comments are used to add explanations, notes, or reminders to the code without affecting
its execution. Comments are very helpful for documenting your SQL queries or scripts, especially
when working on complex code, or when sharing SQL with others.
1. Single-Line Comments
Single-line comments are used for short explanations or notes that apply to only one line of code. In
SQL, they are marked with either:
Syntax:
-- This is a single-line comment
Example:
-- Select all rows from the customers table
SELECT * FROM customers;
Both of these comments will be ignored by the SQL engine and will not affect the execution of the
code.
2. Multi-Line Comments
Multi-line comments are used for comments that span multiple lines. They begin with /* and end
with */. This allows you to comment out larger sections of code or provide more detailed
documentation.
Syntax:
/*
This is a multi-line comment.
It can span multiple lines.
Everything between the opening '/*' and closing '*/' will be treated as a comment.
*/
Example:
/*
This query selects all data from the employees table.
It retrieves employee names, departments, and hire dates.
*/
SELECT name, department, hire_date FROM employees;
You can also use multi-line comments to comment out blocks of SQL code temporarily:
/*
SELECT * FROM employees;
SELECT * FROM customers;
*/
In this case, both SELECT statements are commented out, and the SQL engine will ignore them
during execution.
3. Inline Comments
You can also add comments at the end of a line of SQL code. This is often used to explain or clarify
individual components of a query. To do this, simply add a comment after the SQL code on the same
line, starting with --.
Example:
SELECT name, age, salary FROM employees -- Fetch employee details
WHERE age > 30; -- Only employees older than 30
1. Code Readability: Comments make your code easier to understand, especially for other
developers or for you when you return to it after some time.
2. Documentation: They allow you to explain why certain queries are structured the way they
are, or why certain conditions are used.
3. Debugging: You can comment out parts of a query for debugging purposes.
4. Code Maintenance: In large projects, comments help track changes and provide context for
why certain decisions were made.
Database
To create a database known as classpractice
create database classpractice;
These tables will be related through foreign keys to demonstrate how relationships are established
in an SQL environment.
1. Users Table
The Users table will store information about users, such as their name, email, and date of birth.
2. Products Table
The Products table will store information about products, such as the product name, description,
and price.
3. Orders Table
The Orders table will store information about customer orders, including a reference to the user
who placed the order and the product they ordered. This table will have foreign keys to the
Users and Products tables.
The DESCRIBE command (or EXPLAIN) provides a detailed description of the structure of a table.
It shows the column names, data types, nullability, keys, and other details.
DESCRIBE Users;
or
EXPLAIN Users;
Result Example:
1. Navigate to the "Schemas" panel: On the left side of the MySQL Workbench, you will see a
"Schemas" panel listing all databases.
2. Expand your database: Find the database that contains the Users table and click the plus
sign (+) to expand it.
3. View the Tables: Under the expanded database, find and right-click on the Users table.
4. Select "Table Inspector": Right-click on the Users table and choose "Table Inspector"
from the context menu.
o This will open a new window displaying the schema of the Users table, including
columns, indexes, foreign keys, and more.
Method 3: Use SHOW CREATE TABLE Command
To see the full CREATE TABLE statement (including all constraints and indexes), you can use the
SHOW CREATE TABLE command:
This will return the SQL statement used to create the table, including all column definitions,
primary keys, foreign keys, and any other table attributes.
Example:
| Table | Create
Table
|
| Users | CREATE TABLE `Users` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(100) DEFAULT NULL,
`last_name` varchar(100) DEFAULT NULL,
`email` varchar(100) NOT NULL,
`date_of_birth` date DEFAULT NULL,
PRIMARY KEY (`user_id`),
UNIQUE KEY `email` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 |
This statement shows the column definitions, primary key, and unique key, as well as other table
settings like the storage engine (InnoDB) and character set.
If you're not seeing the EER Model option in MySQL Workbench, it's likely that you're using a
version of MySQL Workbench where the EER Model feature is located elsewhere, or you may need
to create a new Model to visualize your database structure. Let's go through a more detailed step-
by-step guide for creating an EER diagram in MySQL Workbench, which will allow you to visualize
your tables and relationships.
How to Create an EER Diagram in MySQL Workbench
1. Open MySQL Workbench:
o Launch MySQL Workbench and connect to your MySQL server.
2. Create a New Model: If the "EER Model" is not showing, you can manually create a new
model from the "Model" menu.
o Go to the "File" menu at the top-left corner of MySQL Workbench.
o Click on "File" → "New Model". This will create a new model file for you to work
with.
o A new tab will open with an empty model layout.
3. Add Your Existing Database: You will now want to import the schema (the tables) from
your MySQL database into the model.
o On the right-hand side of the Model tab, you should see an option that says "Add
Table" or "Database".
o Click on the Database icon (a cylinder symbol) on the left panel, and then select
"Reverse Engineer" to import your existing schema (tables) into the model.
4. Reverse Engineer Your Database:
o When prompted, choose "Reverse Engineer" to start the process.
o In the wizard that appears, select your MySQL connection (the one that connects to
your running MySQL server).
o Click Next and proceed to choose the schema (your database) that you want to work
with.
o After selecting your database, click Next to start the process. Workbench will fetch
all tables, relationships, and other database objects.
5. Generate the Diagram:
o Once the reverse engineering process is complete, MySQL Workbench will import
your tables and automatically generate an EER Diagram showing the relationships
(foreign keys) between them.
o The tables will be displayed in the workspace, and relationships will be represented
with lines connecting the relevant columns.
6. View and Adjust the Diagram:
o If the tables aren't automatically arranged neatly, you can drag them around in the
workspace to make the diagram easier to read.
o You’ll see the lines connecting the Orders table to the Users table and the Products
table, which represents the foreign key relationships.
7. Save the Diagram:
o After you’re done working with the diagram, you can save the model by clicking File
→ Save Model, which will save your changes in a .mwb file.
o You can later open this file in MySQL Workbench to continue editing or reviewing
the schema and relationships.
Relationships
1. Users ↔ Orders:
o The Orders table has a foreign key (user_id) that references the Users table.
This establishes a one-to-many relationship: one user can place many orders, but
each order belongs to only one user.
2. Products ↔ Orders:
o The Orders table has a foreign key (product_id) that references the Products
table. This creates a one-to-many relationship as well: one product can be ordered
many times, but each order refers to a single product.
To view the records you have keyed in type the code below
Select * from users;
Select * from products;
Select * from orders;
Let's go over how to use the different types of JOIN operations to query the tables we created (Users,
Products, and Orders).
These joins will help you combine data from multiple tables based on the relationships between them.
We already know that:
• The Orders table has a foreign key relationship to the Users table (user_id).
• The Orders table has a foreign key relationship to the Products table (product_id).
1. INNER JOIN
An INNER JOIN returns only the rows that have matching values in both tables. It excludes rows where there
is no match.
Example: Retrieve all orders along with user information and product details.
Explanation:
• The query retrieves all orders (Orders table), along with the corresponding user (Users table) and
product (Products table) details.
• The INNER JOIN ensures that only orders with matching users and products are included.
SELECT
o.order_id,
u.first_name,
u.last_name,
p.product_name,
o.order_date,
o.quantity
FROM Orders o
INNER JOIN Users u ON o.user_id = u.user_id
INNER JOIN Products p ON o.product_id = p.product_id;
Explanation of the query
This SQL query retrieves information about orders, users, and products by joining three tables: Orders, Users,
and Products. Let's break it down:
Breakdown of the Query:
1. SELECT Clause:
• o.order_id: Selects the order_id from the Orders table (aliased as o).
• u.first_name: Selects the first_name from the Users table (aliased as u).
• u.last_name: Selects the last_name from the Users table.
• p.product_name: Selects the product_name from the Products table (aliased as p).
• o.order_date: Selects the order_date from the Orders table.
• o.quantity: Selects the quantity of products ordered from the Orders table.
2. FROM Clause:
• FROM Orders o: This specifies the primary table is Orders, which is aliased as o for
convenience in referencing its columns.
3. INNER JOINs:
• INNER JOIN Users u ON o.user_id = u.user_id: This joins the Orders table to the Users table,
linking them through the user_id field, which exists in both tables. This allows retrieving
user details (like first_name and last_name) for each order.
• INNER JOIN Products p ON o.product_id = p.product_id: This joins the Orders table to
the Products table, linking them through the product_id field, which exists in both tables.
This allows retrieving product details (like product_name) for each order.
What the Query Does:
The query will return a result set that includes the following details for each order:
• The order_id of the order.
• The first_name and last_name of the user who placed the order.
• The product_name of the product that was ordered.
• The order_date (when the order was placed).
• The quantity (how many of that product was ordered).
Explanation:
• The LEFT JOIN ensures that all orders are returned, even if there is no matching user or product for
an order.
• If an order has no corresponding user or product, those columns will have NULL values.
SELECT
o.order_id,
u.first_name,
u.last_name,
p.product_name,
o.order_date,
o.quantity
FROM Orders o
LEFT JOIN Users u ON o.user_id = u.user_id
LEFT JOIN Products p ON o.product_id = p.product_id;
Explanation of the query
Breakdown of the Query:
1. SELECT Clause:
• The selected columns are the same as in the previous query:
• o.order_id: From the Orders table.
• u.first_name: From the Users table.
• u.last_name: From the Users table.
• p.product_name: From the Products table.
• o.order_date: From the Orders table.
• o.quantity: From the Orders table.
2. FROM Clause:
• FROM Orders o: The primary table is Orders, aliased as o.
3. LEFT JOINs:
• LEFT JOIN Users u ON o.user_id = u.user_id: This performs a left join between
the Orders table and the Users table on the user_id field. A left join means:
• If there is a matching user_id in both the Orders and Users tables, it will return the
corresponding user data (e.g., first_name, last_name).
• If there is no matching user_id in the Users table for a given order, the query will
still return that order, but the user fields (first_name, last_name) will be NULL.
• LEFT JOIN Products p ON o.product_id = p.product_id: This performs a left join between
the Orders table and the Products table on the product_id field. Similarly, it behaves as
follows:
• If there is a matching product_id in both the Orders and Products tables, it will
return the corresponding product_name.
• If there is no matching product_id in the Products table, the product_name will
be NULL.
What the Query Does:
• The query will return the same set of columns as the previous query (order ID, user details, product
name, order date, and quantity).
• The key difference is that it uses LEFT JOINs, meaning:
• If an order exists without a matching user or a matching product, it will still be included in
the result set.
• For orders that don't have a corresponding user or product in the database,
the first_name, last_name, or product_name fields will be NULL.
NOTE BETTER: HOW TO KNOW WHICH IS THE LEFT TABLE AND WHICH IS THE RIGHT TABLE
Explanation:
• In this part of the query, you're doing a LEFT JOIN between Orders and Users.
o The left table is Orders because it appears first in the LEFT JOIN.
o The right table is Users because it appears second.
This means that all rows from the Orders table will be included, even if there is no corresponding row in the
Users table. If there's no matching user_id for an order, the Users columns (like first_name, last_name) will be
NULL.
Explanation:
• In this part of the query, you're doing another LEFT JOIN, but this time between Orders and
Products.
o The left table is still Orders, because Orders is the first table mentioned in this join clause.
o The right table is Products because it is the second table in this join clause.
This means that all rows from the Orders table will be included in the result, even if there is no matching
product_id in the Products table. If there's no corresponding product, the Products columns (like
product_name) will be NULL.
Final Outcome:
• The query will return all rows from the Orders table, along with matching Users and Products data (if
available).
• If there is no matching user for an order, the first_name and last_name columns will be NULL.
• If there is no matching product for an order, the product_name column will be NULL.
In Summary:
SELECT
p.product_id,
p.product_name,
o.order_id,
o.order_date,
o.quantity
FROM Products p
RIGHT JOIN Orders o ON p.product_id = o.product_id;
UNION
SELECT
o.order_id,
u.first_name,
u.last_name,
p.product_name,
o.order_date,
o.quantity
FROM Orders o
RIGHT JOIN Users u ON o.user_id = u.user_id
RIGHT JOIN Products p ON o.product_id = p.product_id;
Explanation:
• The first part of the query (LEFT JOIN) ensures that all orders, users, and products are returned, even
if there is no matching product or user.
• The second part (RIGHT JOIN) ensures that all users and products are returned, even if there is no
matching order for them.
• UNION combines the results of both parts while removing duplicates.
mysql> commit;
Query OK, 0 rows affected (0.01 sec)
mysql> rollback;
Query OK, 0 rows affected (0.04 sec)