viernes, 23 de mayo de 2025
Date Practice
martes, 6 de mayo de 2025
Date time type
| Data Type | “Zero” Value |
|---|---|
DATE | '0000-00-00' |
TIME | '00:00:00' |
DATETIME | '0000-00-00 00:00:00' |
TIMESTAMP | '0000-00-00 00:00:00' |
YEAR | 0000 |
Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT
Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT
MySQL supports the SQL standard integer types INTEGER (or INT) and SMALLINT. As an extension to the standard, MySQL also supports the integer types TINYINT, MEDIUMINT, and BIGINT. The following table shows the required storage and range for each integer type.
Table 13.1 Required Storage and Range for Integer Types Supported by MySQL
| Type | Storage (Bytes) | Minimum Value Signed | Minimum Value Unsigned | Maximum Value Signed | Maximum Value Unsigned |
|---|---|---|---|---|---|
TINYINT | 1 | -128 | 0 | 127 | 255 |
SMALLINT | 2 | -32768 | 0 | 32767 | 65535 |
MEDIUMINT | 3 | -8388608 | 0 | 8388607 | 16777215 |
INT | 4 | -2147483648 | 0 | 2147483647 | 4294967295 |
BIGINT | 8 | -263 | 0 | 263-1 | 264-1 |
viernes, 18 de abril de 2025
MySQL ANY ALL IN
mysql> select 4 >any(select 33 as V UNION ALL select 11) as R;
+---+
| R |
+---+
| 0 |
+---+
1 row in set (0.00 sec)
mysql> select 34 >any(select 33 as V UNION ALL select 11) as R;
+---+
| R |
+---+
| 1 |
+---+
1 row in set (0.01 sec)
Syntax:
operand comparison_operator ANY (subquery)
operand IN (subquery)
operand comparison_operator SOME (subquery)Where comparison_operator is one of these operators:
= > < >= <= <> !=MySQL exists
select exists (select 'A' where 5>10) as R;
+---+
| R |
+---+
| 0 |
+---+
MySQL IF
mysql> select if(10>8,'A','B') as result;
+--------+
| result |
+--------+
| A |
+--------+
MySQL case
mysql> set @i=4;
mysql> select case @i
-> when @i>3 then'A'
-> else 'B'
-> end as t;
lunes, 17 de marzo de 2025
Functions and Operators
Functions and Operators
https://dev.mysql.com/doc/refman/8.4/en/functions.html
Data type
https://dev.mysql.com/doc/refman/8.4/en/data-types.html
sábado, 18 de enero de 2025
books
https://github.com/manjunath5496/MySQL-Books/blob/master/README.md
lunes, 13 de enero de 2025
join
CREATE TABLE members (
member_id INT AUTO_INCREMENT,
name VARCHAR(100),
PRIMARY KEY (member_id)
);
CREATE TABLE committees (
committee_id INT AUTO_INCREMENT,
name VARCHAR(100),
PRIMARY KEY (committee_id)
);Code language: SQL (Structured Query Language) (sql)Second, insert some rows into the tables members and committees :
INSERT INTO members(name)
VALUES('John'),('Jane'),('Mary'),('David'),('Amelia');
INSERT INTO committees(name)
VALUES('John'),('Mary'),('Amelia'),('Joe');
mysql> SELECT * FROM members;
+-----------+--------+
| member_id | name |
+-----------+--------+
| 1 | John |
| 2 | Jane |
| 3 | Mary |
| 4 | David |
| 5 | Amelia |
+-----------+--------+
5 rows in set (0.00 sec)
mysql> SELECT * FROM committees;
+--------------+--------+
| committee_id | name |
+--------------+--------+
| 1 | John |
| 2 | Mary |
| 3 | Amelia |
| 4 | Joe |
+--------------+--------+
4 rows in set (0.00 sec)
mysql> select m.member_id,c.committee_id,m.name,c.name from members m inner join committees as c on c.name=m.name;
+-----------+--------------+--------+--------+
| member_id | committee_id | name | name |
+-----------+--------------+--------+--------+
| 1 | 1 | John | John |
| 3 | 2 | Mary | Mary |
| 5 | 3 | Amelia | Amelia |
+-----------+--------------+--------+--------+
3 rows in set (0.01 sec)
mysql> select m.member_id,c.committee_id,m.name,c.name from members m left join committees as c on c.name=m.name;
+-----------+--------------+--------+--------+
| member_id | committee_id | name | name |
+-----------+--------------+--------+--------+
| 1 | 1 | John | John |
| 2 | NULL | Jane | NULL |
| 3 | 2 | Mary | Mary |
| 4 | NULL | David | NULL |
| 5 | 3 | Amelia | Amelia |
+-----------+--------------+--------+--------+
5 rows in set (0.00 sec)
mysql> select m.member_id,c.committee_id,m.name,c.name from members m right join committees as c on c.name=m.name;
+-----------+--------------+--------+--------+
| member_id | committee_id | name | name |
+-----------+--------------+--------+--------+
| 1 | 1 | John | John |
| 3 | 2 | Mary | Mary |
| 5 | 3 | Amelia | Amelia |
| NULL | 4 | NULL | Joe |
+-----------+--------------+--------+--------+
4 rows in set (0.00 sec)
mysql> SELECT * FROM members where name not in(SELECT name FROM committees);
+-----------+-------+
| member_id | name |
+-----------+-------+
| 2 | Jane |
| 4 | David |
+-----------+-------+
2 rows in set (0.01 sec)
mysql> select * from committees where name not in ( select name from members);
+--------------+------+
| committee_id | name |
+--------------+------+
| 4 | Joe |
+--------------+------+
1 row in set (0.00 sec)
Code language: SQL (Structured Query Language) (sql)
sábado, 28 de diciembre de 2024
testing null
mysql> SELECT product_id,if(isnull(price)=0,'A','B') as p from products;
lunes, 25 de noviembre de 2024
Prepare statement
-- Step 1: Prepare an INSERT statement to insert a user into the users table
PREPARE insert_stmt FROM 'INSERT INTO users (name, email) VALUES (?, ?)';
-- Step 2: Set values for placeholders
SET @name = 'John Doe', @email = 'john.doe@example.com';
-- Step 3: Execute the prepared INSERT statement with the provided values
EXECUTE insert_stmt USING @name, @email;
-- Step 4: Deallocate the prepared INSERT statement
DEALLOCATE PREPARE insert_stmt;
-- Step 5: Prepare a SELECT statement to retrieve user by ID
PREPARE select_stmt FROM 'SELECT id, name, email FROM users WHERE id = ?';
-- Step 6: Set the value for the ID of the user to retrieve
SET @id = 1;
-- Step 7: Execute the SELECT statement with the ID
EXECUTE select_stmt USING @id;
-- Step 8: Deallocate the prepared SELECT statement
DEALLOCATE PREPARE select_stmt;
lunes, 18 de noviembre de 2024
MySQL Transactions
In MySQL, transactions allow you to group multiple SQL statements into a single unit of work. This ensures that the changes made by those statements are executed together, and if something goes wrong, the transaction can be rolled back to maintain data integrity. Transactions are especially useful when you need to perform a series of operations that should either all succeed or all fail.
Basic Commands for MySQL Transactions
Start a Transaction
To start a transaction, you use theSTART TRANSACTIONorBEGINcommand.
To save all the changes made during the transaction, you use the
COMMIT command. Once a transaction is committed, the changes become permanent.3 Rollback a Transaction
If something goes wrong during the transaction (e.g., a constraint violation), you can use the ROLLBACK command to undo all the changes made since the transaction started.
ROLLBACK;
4 Savepoints
A savepoint allows you to create a point within a transaction to which you can roll back without affecting the entire transaction.
SAVEPOINT savepoint_name;
By default, MySQL runs in autocommit mode, meaning every SQL statement is treated as a transaction. If you want to disable autocommit for your session (so you can manually manage transactions), use the following command:
In the above example:
- We start a transaction with
START TRANSACTION. - We perform some
INSERToperations. - If everything is successful, we use
COMMITto save the changes to the database. - If an error occurs during the transaction (e.g., inserting invalid data), we could roll back the transaction with
ROLLBACKto ensure the database stays in a consistent state.
Isolation Levels in MySQL
MySQL supports different transaction isolation levels, which control the visibility of changes made within a transaction to other transactions. The isolation level can be set as follows:
Here are the available isolation levels:
- READ UNCOMMITTED: Transactions can see uncommitted changes made by other transactions.
- READ COMMITTED: Transactions can only see committed changes from other transactions.
- REPEATABLE READ: Ensures that if a transaction reads a value, it will see the same value if it reads it again later. This is the default isolation level in MySQL.
- SERIALIZABLE: The highest isolation level. It ensures no other transactions can read, write, or even lock the same rows.
Example:
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
Key Points to Remember
- Atomicity: A transaction ensures that all the changes are applied or none at all. If a transaction is rolled back, none of the operations will take effect.
- Consistency: Transactions bring the database from one valid state to another, ensuring integrity.
- Isolation: Transactions are isolated from each other. Depending on the isolation level, the changes in one transaction may or may not be visible to others.
- Durability: Once a transaction is committed, the changes are permanent, even if the system crashes.
Conclusion
Transactions in MySQL are essential for maintaining data integrity and consistency, especially in systems where multiple operations need to be executed together. By using START TRANSACTION, COMMIT, and ROLLBACK, you can ensure that your database operations are reliable and robust.
domingo, 27 de octubre de 2024
Foreign Key
1. What is a Foreign Key?
A FOREIGN KEY in SQL is a constraint that creates a relationship between two tables. It links a column or group of columns in one table (child table) to a primary key or unique key in another table (parent table). This ensures referential integrity, meaning that any value in the foreign key column must exist in the primary key column of the parent table.
2. Creating Foreign Keys
Foreign keys can be defined:
- During table creation with the
CREATE TABLEstatement. - After table creation with the
ALTER TABLEstatement.
2.1. Defining a Foreign Key in CREATE TABLE
Here’s the syntax for adding a foreign key while creating a table:
CREATE TABLE child_table (
child_column datatype,
...
FOREIGN KEY (child_column) REFERENCES parent_table(parent_column)
);
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
name VARCHAR(100)
);
Example
CREATE TABLE orders (
order_id INT PRIMARY KEY,
order_date DATE,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
In this example, customer_id in the orders table is a foreign key that references customer_id in the customers table.
2.2. Adding a Foreign Key with ALTER TABLE
To add a foreign key after creating a table, use the ALTER TABLE statement:
sqlALTER TABLE child_table
ADD FOREIGN KEY (child_column) REFERENCES parent_table(parent_column);
Example
sqlALTER TABLE orders
ADD FOREIGN KEY (customer_id) REFERENCES customers(customer_id);
3. Naming Foreign Key Constraints
You can give a foreign key constraint a specific name using the CONSTRAINT keyword. This makes it easier to reference and manage the constraint later.
sqlCREATE TABLE orders (
order_id INT PRIMARY KEY,
order_date DATE,
customer_id INT,
CONSTRAINT fk_customer FOREIGN KEY (customer_id)
REFERENCES customers(customer_id)
);
In this example, the foreign key is named fk_customer.
4. Cascade Options for Foreign Keys
Foreign key constraints can define actions to take when a referenced row in the parent table is updated or deleted. Common cascade options include:
- ON DELETE CASCADE: Deletes all rows in the child table that reference the deleted row in the parent table.
- ALTER TABLE orders ADD FOREIGN KEY (client_id) REFERENCES clients(client_id) ON DELETE CASCADE;
- ON UPDATE CASCADE: Updates the foreign key in the child table if the referenced key in the parent table is updated.
- ON DELETE SET NULL: Sets the foreign key to
NULLin the child table when the referenced row in the parent table is deleted.
- ON DELETE RESTRICT: Prevents the deletion of a row in the parent table if it is referenced in the child table.
- ALTER TABLE orders ADD FOREIGN KEY (client_id) REFERENCES clients(client_id) ON DELETE RESTRICT;
Example with Cascade Options
sqlCREATE TABLE orders (
order_id INT PRIMARY KEY,
order_date DATE,
customer_id INT,
CONSTRAINT fk_customer FOREIGN KEY (customer_id)
REFERENCES customers(customer_id)
ON DELETE CASCADE
ON UPDATE CASCADE
);
In this example:
- If a
customer_idincustomersis deleted, all relatedorderswill also be deleted (ON DELETE CASCADE). - If
customer_idincustomersis updated, thecustomer_idinordersis also updated (ON UPDATE CASCADE).
5. Managing Foreign Keys
Managing foreign keys includes dropping, disabling, and checking for any constraint violations.
5.1 Dropping a Foreign Key
To remove a foreign key constraint, use the DROP command with ALTER TABLE:
sqlALTER TABLE child_table
DROP FOREIGN KEY constraint_name;
Example
sqlALTER TABLE orders
DROP FOREIGN KEY fk_customer;
5.2 Disabling and Enabling Foreign Key Checks
In some databases (like MySQL), you can temporarily disable foreign key checks, which may be helpful for bulk inserts or data migrations.
Disable foreign key checks:
sqlSET foreign_key_checks = 0;Enable foreign key checks:
sqlSET foreign_key_checks = 1;
6. Foreign Key Best Practices
- Use Descriptive Names: Name constraints for easier management.
- Avoid Cascading Deletes in critical tables to prevent accidental data loss.
- Ensure Data Consistency: Insert data in the parent table before inserting in the child table to avoid foreign key violations.
- Indexes on Foreign Keys: In many databases, it’s recommended to index foreign key columns for better query performance.
7. Common Errors and Troubleshooting
Error: "Cannot add or update a child row: a foreign key constraint fails."
- Cause: This occurs if you attempt to add a foreign key value in the child table that doesn’t exist in the parent table.
- Solution: Ensure that the referenced key exists in the parent table.
Error: "Cannot delete or update a parent row: a foreign key constraint fails."
- Cause: This occurs if you attempt to delete or update a row in the parent table that has dependent rows in the child table.
- Solution: Use
ON DELETE CASCADEor manually delete the dependent rows first.
8. Advanced Example: Multiple Foreign Keys
You can create tables with multiple foreign keys, referencing different tables.
sqlCREATE TABLE order_items (
item_id INT PRIMARY KEY,
order_id INT,
product_id INT,
quantity INT,
FOREIGN KEY (order_id) REFERENCES orders(order_id) ON DELETE CASCADE,
FOREIGN KEY (product_id) REFERENCES products(product_id) ON DELETE SET NULL
);
In this example:
order_idreferencesorders, and if an order is deleted, the relatedorder_itemsentries are also deleted.product_idreferencesproducts, and if a product is deleted,product_idis set toNULLinorder_items.
Get the list of tables in your database:
1) SHOW TABLES;2) SHOW CREATE TABLE table_name;ALTER TABLE group_members ADD CONSTRAINT fk_group_id FOREIGN KEY (group_id) REFERENCES call_groups(group_id) ON DELETE CASCADE ON UPDATE CASCADE;Summary
- Foreign keys maintain relationships and referential integrity between tables.
- Cascade options (
ON DELETE,ON UPDATE) allow flexibility in handling parent-child table relationships. - Naming constraints and indexing foreign key columns can improve readability and performance.
- Disable foreign key checks temporarily when performing bulk operations if necessary.
With this guide, you should be well-equipped to define and manage foreign keys effectively in SQL databases!
sábado, 26 de octubre de 2024
INNER JOINS
mysql> select * from sales;
+----+--------------+-------------+
| id | product_name | sale_amount |
+----+--------------+-------------+
| 1 | Product A | 100.50 |
| 2 | Product B | 75.25 |
| 3 | Product A | 120.75 |
| 4 | Product C | 50.00 |
| 5 | Product B | 90.80 |
| 6 | Product R | 300.00 |
+----+--------------+-------------+
6 rows in set (0.00 sec)
mysql> select * from clients;
+-----------+-------------+-------------------+
| client_id | client_name | registration_date |
+-----------+-------------+-------------------+
| 1 | Alice | 2023-01-10 |
| 2 | Bob | 2023-02-15 |
| 3 | Charlie | 2023-03-20 |
| 4 | Ambiorix | 2024-10-06 |
| 5 | Many | 2024-10-11 |
+-----------+-------------+-------------------+
5 rows in set (0.00 sec)
mysql> select c.client_name,c.client_id,s.id,s.product_name from clients as c INNER JOIN sales as s on s.id=c.client_id;
+-------------+-----------+----+--------------+
| client_name | client_id | id | product_name |
+-------------+-----------+----+--------------+
| Alice | 1 | 1 | Product A |
| Bob | 2 | 2 | Product B |
| Charlie | 3 | 3 | Product A |
| Ambiorix | 4 | 4 | Product C |
| Many | 5 | 5 | Product B |
+-------------+-----------+----+--------------+
5 rows in set (0.00 sec)
mysql> select c.client_name,c.client_id,s.id,s.product_name from clients as c LEFT JOIN sales as s on s.id=c.client_id;
+-------------+-----------+------+--------------+
| client_name | client_id | id | product_name |
+-------------+-----------+------+--------------+
| Alice | 1 | 1 | Product A |
| Bob | 2 | 2 | Product B |
| Charlie | 3 | 3 | Product A |
| Ambiorix | 4 | 4 | Product C |
| Many | 5 | 5 | Product B |
+-------------+-----------+------+--------------+
5 rows in set (0.00 sec)
mysql> select c.client_name,c.client_id,s.id,s.product_name from clients as c RIGHT JOIN sales as s on s.id=c.client_id;
+-------------+-----------+----+--------------+
| client_name | client_id | id | product_name |
+-------------+-----------+----+--------------+
| Alice | 1 | 1 | Product A |
| Bob | 2 | 2 | Product B |
| Charlie | 3 | 3 | Product A |
| Ambiorix | 4 | 4 | Product C |
| Many | 5 | 5 | Product B |
| NULL | NULL | 6 | Product R |
+-------------+-----------+----+--------------+
sábado, 19 de octubre de 2024
Alter table
https://dev.mysql.com/doc/refman/8.4/en/alter-table.html
https://dev.mysql.com/doc/refman/8.4/en/alter-table-examples.html
lunes, 7 de octubre de 2024
inner and left join 3 tables
$query_ivr = "
SELECT
c.cliente_id,
c.cliente_nombre,
c.cliente_telefono,
c.cliente_blacklist_status,
SUM(co.compra_precio) AS total_compra,
ivr.ivr_num_src,
ivr.ivr_num_dst,
ivr.ivr_caller_channel,
ivr.ivr_call_status,
ivr.ivr_calldate,
b.balance_creditos
FROM
clientes AS c
INNER JOIN
compras AS co ON c.cliente_id = co.compra_cliente_id
INNER JOIN
ivr_calls AS ivr ON ivr.ivr_num_src = c.cliente_telefono AND ivr.ivr_call_status = 1
LEFT JOIN
balance AS b ON b.balance_cliente = c.cliente_id
GROUP BY
c.cliente_id,
c.cliente_nombre,
c.cliente_telefono,
c.cliente_blacklist_status,
ivr.ivr_num_src,
ivr.ivr_num_dst,
ivr.ivr_caller_channel,
ivr.ivr_call_status,
ivr.ivr_calldate,
b.balance_creditos;";
Added a LEFT JOIN:
- The
balancetable is joined withLEFT JOINto ensure that even if there is no corresponding entry in thebalancetable, you still get results from the other tables.
- The
Selected
b.balance_creditos:- This column is included in the
SELECTstatement to retrieve the credit balance for each client.
- This column is included in the
Explanation:
- Using a
LEFT JOINallows you to fetch client information even if they do not have any associated balance records.