mysql

Db2 SQL

Like

SELECT column1, column2
FROM table_name
WHERE column1 LIKE '%pattern%';

Additionally, DB2 supports some additional wildcard characters that can be used with the LIKE operator:

  • _ (underscore): Matches any single character. For example, '_at' will match "cat", "bat", but not "at" or "rat".
  • [] (brackets): Matches any single character within the specified range or set. For example, '[abc]' will match "a", "b", or "c".
  • [^] (caret within brackets): Matches any single character not within the specified range or set. For example, '[^abc]' will match any character except "a", "b", or "c".
SELECT column1, column2
FROM table_name
WHERE column1 LIKE 'prefix%';

SELECT column1, column2
FROM table_name
WHERE column1 LIKE '%suffix';

SELECT column1, column2
FROM table_name
WHERE column1 LIKE '%part1_part2%';

SELECT column1, column2
FROM table_name
WHERE column1 LIKE '_at';

SELECT column1, column2
FROM table_name
WHERE column1 LIKE '[abc]at';

SELECT column1, column2
FROM table_name
WHERE column1 LIKE '[^abc]at';

Auto-incrementing Columns:

MySQL uses the AUTO_INCREMENT keyword to define a column that automatically increments its value for each new row inserted into a table. In DB2, the equivalent functionality is achieved using an identity column, which is defined as GENERATED ALWAYS AS IDENTITY.

Handling of NULL Values:

MySQL treats NULL values in a unique way when it comes to comparisons and sorting. It considers NULL as the lowest possible value, so NULL values come first when sorting in ascending order and last when sorting in descending order. DB2 follows the SQL standard behavior for NULL values, where they are considered unknown and are generally sorted at the end regardless of the sorting order.

String Comparison and Collation:

MySQL provides various collation options to define how string comparisons should be performed, taking into account factors such as case-sensitivity and accent sensitivity. DB2 also supports collations for string comparisons, but the default collation is determined by the database and operating system settings. Changing the collation requires altering the database or table collation settings.

Date and Time Functions:

MySQL and DB2 have some differences in their supported date and time functions. For example, MySQL provides functions like DATE_FORMAT() for formatting dates, UNIX_TIMESTAMP() for retrieving the current Unix timestamp, and NOW() for obtaining the current date and time. DB2 uses different functions, such as VARCHAR_FORMAT() for formatting dates, CURRENT_TIMESTAMP for retrieving the current timestamp, and CURRENT DATE for obtaining the current date.

Pagination Syntax:

When retrieving a limited subset of rows from a query result, MySQL uses the LIMIT clause to specify the number of rows to return and an optional offset to skip rows. In DB2, the equivalent functionality is achieved using the FETCH FIRST clause along with the ROWS keyword to specify the number of rows to return and the OFFSET clause to skip rows.

MySQL Recap, Stored Procedures

SQL

Structured query language

show databases;

use dbname;

show tables;

desc users;
-- use a db
use testdb;

-- use a delimter
delimiter $$

create procedure HelloWorld()
begin
select "Hello WOlrd!";
end$$

delimiter ;

drop procedure HelloWorld;

call HelloWorld();

Spring Mysql One to Many....

pom.xml
- lombok
- spring-boot-starter-data-jpa
- mysql-connector-java

application.properties

# MySQL connection properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.url=jdbc:mysql://localhost:3306/testspring

# Log JPA queries
# Comment this in production
spring.jpa.show-sql=true

# Drop and create new tables (create, create-drop, validate, update)
# Only for testing purpose - comment this in production
spring.jpa.hibernate.ddl-auto=create-drop

# Hibernate SQL dialect
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

ResApplication.java

public class RestApplication {

    public static void main(String[] args) {
        SpringApplication.run(RestApplication.class, args);
    }

    @Bean
    public CommandLineRunner mappingDemo(BookRepository bookRepository,
                                         PageRepository pageRepository) {
        return args -> {

            // create a new book
            Book book = new Book("Java 101", "John Doe", "123456");

            // save the book
            bookRepository.save(book);
            pageRepository.save(new Page(65, "Java 8 contents", "Java 8", book));
            pageRepository.save(new Page(95, "Concurrency contents", "Concurrency", book));
        };
    }
}

Book.java


@Entity @Table(name = "books") @Getter @Setter public class Book implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String title; private String author; @Column(unique = true) private String isbn; ```**```@JsonManagedReference```**``` @OneToMany(mappedBy = "book", fetch = FetchType.LAZY, cascade = CascadeType.ALL) private List<Page> pages = new ArrayList<Page>(); public Book() { } public Book(String title, String author, String isbn) { this.title = title; this.author = author; this.isbn = isbn; } // getters and setters, equals(), toString() .... (omitted for brevity) @Override public String toString() { return "Book{" + "id=" + id + ", title='" + title + '\'' + ", author='" + author + '\'' + ", isbn='" + isbn + '\'' + ", number of pages=" + pages.size() + '}'; } }

Pages.java


@Entity @Table(name = "pages") @Setter @Getter public class Page implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private int number; private String content; private String chapter; @JsonBackReference @ManyToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "book_id", nullable = false) private Book book; public Page() { } public Page(int number, String content, String chapter, Book book) { this.number = number; this.content = content; this.chapter = chapter; this.book = book; } // getters and setters, equals(), toString() .... (omitted for brevity) @Override public String toString() { return "Page{" + "id=" + id + ", number=" + number + ", content='" + content + '\'' + ", chapter='" + chapter + '\'' + ", book=" + book.toString() + '}'; } }

BookRepository.java

public interface BookRepository extends CrudRepository<Book, Long> {

    Book findByIsbn(String isbn);
}

PageRepository.java

public interface PageRepository extends CrudRepository<Page, Long> {

    List<Page> findByBook(Book book, Sort sort);
}

BooksController.java


@RestController @RequestMapping(value = "/books", produces = MediaType.APPLICATION_JSON_VALUE) public class BooksController { private final BookRepository bookRepository; private final PageRepository pageRepository; public BooksController(BookRepository bookRepository, PageRepository pageRepository) { this.bookRepository = bookRepository; this.pageRepository = pageRepository; } @GetMapping(value = "/pages", produces = MediaType.APPLICATION_JSON_VALUE) @ResponseStatus(HttpStatus.OK) public List<Page> pages(){ List<Page> result = (List<Page>) pageRepository.findAll(); System.out.println(result); System.out.println(result.get(0)); return result; } @GetMapping("/") public List<Book> books(){ return (List<Book>)bookRepository.findAll(); } }

http://localhost:8080/books/

[
{
"id": 1,
"title": "Java 101",
"author": "John Doe",
"isbn": "123456",
"pages": [
{
"id": 1,
"number": 1,
"content": "Introduction contents",
"chapter": "Introduction"
},
{
"id": 2,
"number": 65,
"content": "Java 8 contents",
"chapter": "Java 8"
},
{
"id": 3,
"number": 95,
"content": "Concurrency contents",
"chapter": "Concurrency"
}
]
}
]

http://localhost:8080/books/pages

[
{
"id": 1,
"number": 1,
"content": "Introduction contents",
"chapter": "Introduction"
},
{
"id": 2,
"number": 65,
"content": "Java 8 contents",
"chapter": "Java 8"
},
{
"id": 3,
"number": 95,
"content": "Concurrency contents",
"chapter": "Concurrency"
}
]

dotnet core notes

localize date time
CultureInfo ci = new CultureInfo("nl-NL");Console.WriteLine(DateTime.Now.ToString("D", ci));

scaffold mysql db
dotnet ef dbcontext scaffold "server=localhost;port=3306;user=root;password=root;database=opit" MySql.Data.EntityFrameworkCore -o Models -f

Dotnet core links

Dotnet Identity & mySQL

working identity with pomelo in dotnet 2.1

Nice article dotnet core 2 with link sql creation file

identity proj

implementing Identity storage provider

UPDATE mysql.user SET Password=PASSWORD('root') WHERE User='root'; 

or

 ALTER USER 'root'@'localhost' IDENTIFIED BY 'root';
docker exec -i mysql-server mysql -uroot -p"root" mysql < orkestpit.sql

with homebew:

brew tap homebrew/services
brew services list
brew install mysql@5.7
brew services start mysql
mysql_secure_installation

echo 'export PATH="/usr/local/opt/mysql@5.7/bin:$PATH"' >> ~/.bash_profile
source ~/.bash_profile
mysql -V

Mysql General notes

cheat sheet MySQL

Commands
Access monitor: mysql -u [username] -p; (will prompt for password)

Show all databases: show databases;

Access database: mysql -u [username] -p [database] (will prompt for password)

Create new database: create database [database];

Select database: use [database];

Determine what database is in use: select database();

Show all tables: show tables;

Show table structure: describe [table];

List all indexes on a table: show index from [table];

Create new table with columns: CREATE TABLE [table] ([column] VARCHAR(120), [another-column] DATETIME);

Adding a column: ALTER TABLE [table] ADD COLUMN [column] VARCHAR(120);

Adding a column with an unique, auto-incrementing ID: ALTER TABLE [table] ADD COLUMN [column] int NOT NULL AUTO_INCREMENT PRIMARY KEY;

Inserting a record: INSERT INTO [table] ([column], [column]) VALUES ('[value]', [value]');

MySQL function for datetime input: NOW()

Selecting records: SELECT * FROM [table];

Explain records: EXPLAIN SELECT * FROM [table];

Selecting parts of records: SELECT [column], [another-column] FROM [table];

Counting records: SELECT COUNT([column]) FROM [table];

Counting and selecting grouped records: SELECT *, (SELECT COUNT([column]) FROM [table]) AS count FROM [table] GROUP BY [column];

Selecting specific records: SELECT * FROM [table] WHERE [column] = [value]; (Selectors: <, >, !=; combine multiple selectors with AND, OR)

Select records containing [value]: SELECT * FROM [table] WHERE [column] LIKE '%[value]%';

Select records starting with [value]: SELECT * FROM [table] WHERE [column] LIKE '[value]%';

Select records starting with val and ending with ue: SELECT * FROM [table] WHERE [column] LIKE '[val_ue]';

Select a range: SELECT * FROM [table] WHERE [column] BETWEEN [value1] and [value2];

Select with custom order and only limit: SELECT * FROM [table] WHERE [column] ORDER BY [column] ASC LIMIT [value]; (Order: DESC, ASC)

Updating records: UPDATE [table] SET [column] = '[updated-value]' WHERE [column] = [value];

Deleting records: DELETE FROM [table] WHERE [column] = [value];

Delete all records from a table (without dropping the table itself): DELETE FROM [table]; (This also resets the incrementing counter for auto generated columns like an id column.)

Delete all records in a table: truncate table [table];

Removing table columns: ALTER TABLE [table] DROP COLUMN [column];

Deleting tables: DROP TABLE [table];

Deleting databases: DROP DATABASE [database];

Custom column output names: SELECT [column] AS [custom-column] FROM [table];

Export a database dump (more info here): mysqldump -u [username] -p [database] > db_backup.sql

Use --lock-tables=false option for locked tables (more info here).

Import a database dump (more info here): mysql -u [username] -p -h localhost [database] < db_backup.sql

Logout: exit;

Aggregate functions
Select but without duplicates: SELECT distinct name, email, acception FROM owners WHERE acception = 1 AND date >= 2015-01-01 00:00:00

Calculate total number of records: SELECT SUM([column]) FROM [table];

Count total number of [column] and group by [category-column]: SELECT [category-column], SUM([column]) FROM [table] GROUP BY [category-column];

Get largest value in [column]: SELECT MAX([column]) FROM [table];

Get smallest value: SELECT MIN([column]) FROM [table];

Get average value: SELECT AVG([column]) FROM [table];

Get rounded average value and group by [category-column]: SELECT [category-column], ROUND(AVG([column]), 2) FROM [table] GROUP BY [category-column];

Multiple tables
Select from multiple tables: SELECT [table1].[column], [table1].[another-column], [table2].[column] FROM [table1], [table2];

Combine rows from different tables: SELECT * FROM [table1] INNER JOIN [table2] ON [table1].[column] = [table2].[column];

Combine rows from different tables but do not require the join condition: SELECT * FROM [table1] LEFT OUTER JOIN [table2] ON [table1].[column] = [table2].[column]; (The left table is the first table that appears in the statement.)

Rename column or table using an alias: SELECT [table1].[column] AS '[value]', [table2].[column] AS '[value]' FROM [table1], [table2];

Users functions
List all users: SELECT User,Host FROM mysql.user;

Create new user: CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';

Grant ALL access to user for * tables: GRANT ALL ON database.* TO 'user'@'localhost';

Find out the IP Address of the Mysql Host
SHOW VARIABLES WHERE Variable_name = 'hostname'; (source)

Sizes databases

SELECT table_schema AS "Database",
ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS "Size (MB)"
FROM information_schema.TABLES
GROUP BY table_schema;

index, indices, indexes
alter table book add index idx_name(name)
alter table book drop index idx_name

multiple row updates at same time
set sql_save_updates=0

check
SHOW VARIABLES LIKE 'sql_safe_updates'

renumber id column
SET @i=0;
UPDATE table_name SET column_name=(@i:=@i+1);

set @rank=0;select @rank:=@rank+1 as rank , screenname, score from gameScore order by score desc;

select groep , screenname from user where userGroup.groep < 98 order by groep;

Explain Select

explain select  count(*) from `tuinhokmetingen`.`AspNetUsers`;

Show create

show create TABLE `temperatures`;

Tags: 

port mysql

SHOW GLOBAL VARIABLES LIKE 'PORT';

Tags: 

size databases

SELECT table_schema AS `Database`,
SUM(data_length + index_length) / 1024 / 1024 AS `Size in MB`
FROM information_schema.TABLES
GROUP BY table_schema;

Tags: 

show column names containing %..%

show column names met naam %rekening%

SELECT table_name, column_name
FROM information_schema.columns
WHERE column_name LIKE '%rekening%'
LIMIT 0 , 30

Tags: 
Subscribe to RSS - mysql