viernes, 23 de mayo de 2025

Date Practice

SELECT 
    NOW() AS Today,
    DATE_SUB(NOW(), INTERVAL 1 DAY) AS Yesterday,
    DATE_ADD(NOW(), INTERVAL 1 DAY) AS Tomorrow,
    ADDTIME(NOW(), '01:01:00') AS Today_1_Hour_1_Min,
    DATEDIFF(NOW(), DATE_SUB(NOW(), INTERVAL 13 DAY)) AS Days_Difference_Between_2_Dates;




mysql> select now() Today,date_sub(now(),interval 1 day) Yesterday, date_add(now(),interval 1 day) Tomorrow,addtime(now(),'1:1') today_1_hour_1_min,datediff(now(),date_sub(now(),interval 13 day)) days_difference_between_2_dates\G;
*************************** 1. row ***************************
                          Today: 2025-05-24 01:25:42
                      Yesterday: 2025-05-23 01:25:42
                       Tomorrow: 2025-05-25 01:25:42
             today_1_hour_1_min: 2025-05-24 02:26:42
days_difference_between_2_dates: 13


---------------

Date format

mysql> select date_format(now(),'%a-%d-%b-%Y') TODAY;
+-----------------+
| TODAY           |
+-----------------+
| Sat-24-May-2025 |
+-----------------+


select FROM_UNIXTIME(1447430881,'%a-%d-%b-%Y') TODAY;
+-----------------+
| TODAY           |
+-----------------+
| Fri-13-Nov-2015 |
+-----------------+
https://dev.mysql.com/doc/refman/8.0/en/date-and-time-functions.html

martes, 6 de mayo de 2025

Date time type

 

Data TypeZero Value
DATE'0000-00-00'
TIME'00:00:00'
DATETIME'0000-00-00 00:00:00'
TIMESTAMP'0000-00-00 00:00:00'
YEAR0000


https://dev.mysql.com/doc/refman/8.0/en/date-and-time-types.html

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 TINYINTMEDIUMINT, 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

TypeStorage (Bytes)Minimum Value SignedMinimum Value UnsignedMaximum Value SignedMaximum Value Unsigned
TINYINT1-1280127255
SMALLINT2-3276803276765535
MEDIUMINT3-83886080838860716777215
INT4-2147483648021474836474294967295
BIGINT8-2630263-1264-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)

-----------
ALL

mysql> select  34 >ALL(select 33  as V UNION ALL select 11) as R;
+---+
| R |
+---+
| 1 |
+---+
1 row in set (0.00 sec)


https://dev.mysql.com/doc/refman/8.4/en/any-in-some-subqueries.html

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 |

+---+


Because     the evaluated query return   empty set, if return any value doesn't matter the value   it will return  1, doesn't matter if is null or 0.

select  'A' where 5>10;
Empty set (0.00 sec)


------------------------    exists   here will return 1

select  exists  (select  NULL) as R;
+------+
| R    |
+------+
|    1 |
+------+
1 row in set (0.00 sec)

-


 select  exists  (select  0) as R;
+---+
| R |
+---+
| 1 |
+---+


select 'Ambiorix' where exists(select 1);
+----------+
| Ambiorix |
+----------+
| Ambiorix |
+----------+

MySQL IF

mysql> select if(10>8,'A','B') as result;

+--------+

| result |

+--------+

| A      |

+--------+


--------------
mysql> select if(10>15,'A','B') as result;
+--------+
| result |
+--------+
| B      |
+--------+


MySQL case

mysql> set @i=4;

 mysql> select case @i

    -> when @i>3 then'A'

    -> else 'B'

    -> end as t;



------------
mysql> select case
    -> when 5>4 then  'A'
    -> when 5<6 then 'B'
    -> else 'C'
    -> end as t;
+---+

select upper(case when 3> 2 then 'h' when 5>1 then 'e' else 'r' end) as Letter;
+--------+
| Letter |
+--------+
| H      |
+--------+

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;

---------

mysql> SELECT product_id,isnull(price) as p from products;
+------------+---+
| product_id | p |
+------------+---+
|          1 | 0 |
|          2 | 0 |
|          3 | 0 |
+------------+---+
3 rows in set (0.00 sec)


mysql> SELECT IF(NULL = NULL, 1, 3);
+-----------------------+
| IF(NULL = NULL, 1, 3) |
+-----------------------+
|                     3 |
+-----------------------+
1 row in set (0.00 sec)

mysql> SELECT IF(NULL is NULL, 1, 3);
+------------------------+
| IF(NULL is NULL, 1, 3) |
+------------------------+
|                      1 |
+------------------------+

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

  1. Start a Transaction
    To start a transaction, you use the START TRANSACTION or BEGIN command.

START TRANSACTION;

2 Commit a Transaction
To save all the changes made during the transaction, you use the COMMIT command. Once a transaction is committed, the changes become permanent.

COMMIT;

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;

If you want to roll back to a specific savepoint:

ROLLBACK TO SAVEPOINT savepoint_name;

5 Autocommit Mode
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:

SET autocommit = 0;

To re-enable autocommit, use:

SET autocommit = 1;

Example of Using Transactions in MySQL

START TRANSACTION;

-- Insert data into a table
INSERT INTO accounts (account_id, balance) VALUES (1, 500);
INSERT INTO accounts (account_id, balance) VALUES (2, 300);

-- Simulate an error (e.g., a constraint violation)
-- For example, inserting an invalid value
-- INSERT INTO accounts (account_id, balance) VALUES (NULL, 'invalid_balance');

-- If no error occurs, commit the transaction
COMMIT;

In the above example:

  1. We start a transaction with START TRANSACTION.
  2. We perform some INSERT operations.
  3. If everything is successful, we use COMMIT to save the changes to the database.
  4. If an error occurs during the transaction (e.g., inserting invalid data), we could roll back the transaction with ROLLBACK to 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:

  1. READ UNCOMMITTED: Transactions can see uncommitted changes made by other transactions.
  2. READ COMMITTED: Transactions can only see committed changes from other transactions.
  3. 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.
  4. 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 TABLE statement.
  • After table creation with the ALTER TABLE statement.

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:

sql
ALTER TABLE child_table ADD FOREIGN KEY (child_column) REFERENCES parent_table(parent_column);

Example

sql
ALTER 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.

sql
CREATE 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.
ALTER TABLE orders 
ADD FOREIGN KEY (client_id) REFERENCES clients(client_id) 
ON UPDATE CASCADE;

  • ON DELETE SET NULL: Sets the foreign key to NULL in the child table when the referenced row in the parent table is deleted.
ALTER TABLE orders ADD FOREIGN KEY (client_id) REFERENCES clients(client_id) ON DELETE SET NULL;
  • 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

sql
CREATE 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_id in customers is deleted, all related orders will also be deleted (ON DELETE CASCADE).
  • If customer_id in customers is updated, the customer_id in orders is 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:

sql
ALTER TABLE child_table DROP FOREIGN KEY constraint_name;

Example

sql
ALTER 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:

    sql
    SET foreign_key_checks = 0;
  • Enable foreign key checks:

    sql
    SET 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 CASCADE or manually delete the dependent rows first.

8. Advanced Example: Multiple Foreign Keys

You can create tables with multiple foreign keys, referencing different tables.

sql
CREATE 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_id references orders, and if an order is deleted, the related order_items entries are also deleted.
  • product_id references products, and if a product is deleted, product_id is set to NULL in order_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;";


  1. Added a LEFT JOIN:

    • The balance table is joined with LEFT JOIN to ensure that even if there is no corresponding entry in the balance table, you still get results from the other tables.
  2. Selected b.balance_creditos:

    • This column is included in the SELECT statement to retrieve the credit balance for each client.

Explanation:

  • Using a LEFT JOIN allows you to fetch client information even if they do not have any associated balance records.