Thursday, March 16, 2023

The SELECT Statement in Oracle

The SELECT statement is used to retrieve information from a database. Following the execution of a SELECT statement, a tabular result is held in a result table (called a result set). It allows you to select the table columns depending on a set of criteria.

SELECT statements might be as straightforward as selecting a few columns from a single table. They can also be complex, with several columns and criteria and multiple tables. In this article, I will introduce the basic SELECT statement fetching data from just one table.

SELECT Syntax:

The SELECT statement contains 4 Parts:

SELECT >> COLUMNS >> FROM >>WHERE

The SELECT clause defines which table columns are retrieved. The FROM clause defines which tables are queried. The WHERE clause determines which table rows should be selected and if it is omitted, all table rows are selected.

The basic syntax looks like this:

SELECT Column_Name1, Column_Name2, Column_Name
FROM Table_Name 
WHERE Criteria;

A database consists of one or more tables. Each table is given a distinct name (e.g., “Employee”, “Department”, “Address”). Data records are stored in tables (rows).

Here’s an example of an “Employee” table: You can use the following SQL script to create “Employee” and load the data.

SQL script to create the  “Employee” table.

CREATE TABLE Employee (
    Employeeid Varchar(15) Primary Key,
    Name       Varchar(15),
    LastName   Varchar(15),
    FirstName  Varchar(15),
    Department Varchar(15),
    Dob        Date,
    Salary     Number(8,0)
);

The following INSERT statements will load data into the “Employee” table for the demos in this article.

INSERT INTO Employee (EmployeeId, Name, LastName, FirstName, Department, DOB, Salary)
VALUES ('1001', 'Allen Cox', 'Cox', 'Allen', 'IT', TO_DATE('01-July-1982', 'DD-MM-YYYY'),75000);
INSERT INTO Employee (EmployeeId, Name, LastName, FirstName, Department, DOB, Salary)
VALUES ('1002', 'Dave Carry', 'Carry', 'Dave', 'Sales', TO_DATE('01-Jan-1992', 'DD-MM-YYYY'),70000);
INSERT INTO Employee (EmployeeId, Name, LastName, FirstName, Department, DOB, Salary)
VALUES ('1003', 'Amit Singh','Singh', 'Amit', 'Sales', TO_DATE('20-Oct-1991', 'DD-MM-YYYY'),50000);
INSERT INTO Employee (EmployeeId, Name, LastName, FirstName, Department, DOB, Salary)
VALUES ('1004', 'Rhonda Grant', 'Grant', 'Rhonda', 'Marketing', TO_DATE('15-May-1980', 'DD-MM-YYYY'),60000);
INSERT INTO Employee (EmployeeId, Name, LastName, FirstName, Department, DOB, Salary)
VALUES ('1005', 'Marvin Cox', 'Cox', 'Marvin', 'Marketing', TO_DATE('15-Jan-1985', 'DD-MM-YYYY'),62000);
INSERT INTO Employee (EmployeeId, Name, LastName, FirstName, Department, DOB, Salary)
VALUES ('1006', 'Dave Grant', 'Grant', 'Dave', 'Sales', TO_DATE('05-Oct-1980', 'DD-MM-YYYY'),90000);

This is how the data in the table looks.

EmployeeId

Name

LastName

FirstName

Department

DOB

Salary

1001

Allen Cox

Cox

Allen

IT

01-JUL-82

75000

1002

Dave Carry

Carry

Dave

Sales

01-JAN-92

70000

1003

Amit Singh

Singh

Amit

Sales

20-OCT-91

50000

1005

Marvin Cox

Cox

Marvin

Marketing

15-JAN-85

62000

1006

Dave Grant

Grant

Dave

Sales

05-OCT-80

90000

Let’s write SELECT statements on the above table.

Retrieve Data from a Single Table

The SELECT statement can retrieve data from single or multiple tables; however, all my examples in this article use a single table to focus on the parts of the SELECT statement itself. In a future article, I will cover multiple table queries and how JOIN operators can be used to connect data from multiple tables and then shaped into a single tabular data stream.

Select all columns

An asterisk following the word “SELECT” indicates that all fields that are available should be retrieved (columns).

Using SELECT * in SQL queries is great for doing quick ad hoc work, but for code that will be reused in production, this is a poor practice that should be avoided. Instead of SELECT *, it is recommended to provide the column names you want in the SELECT query. Using column names not only improves efficiency but also makes SQL code easier to understand.

Furthermore, if you use SQL with * in an application such as PeopleSoft code or .NET code and add any new columns to the table or reorder the existing columns, your code may break. It is however, what most people use when exploring data.

The following SELECT statement gets all the columns and rows from the given table. Note that the FROM clause is where you specify the set of data that your query will be using. I will discuss this more when covering JOIN operations.

SELECT  *  
FROM Employee;

This returns:

Graphical user interface, table Description automatically generated

Selecting one or more columns by name

Any database object such as a column name can be named using either quoted or unquoted identifiers. Unquoted identifiers are not case-sensitive. Oracle classifies them as uppercase.  Case is important when using quoted IDs. By enclosing names in double quotation marks, you can give the following names to different objects in the same namespace.

  • “employees”
  • “Employees”
  • “EMPLOYEES”

It is important to note that Oracle reads the following names identically, therefore they cannot be used for various objects in the same namespace:

  • employees
  • EMPLOYEES
  • “EMPLOYEES”

I prefer object names without quotation marks because they are easier for me to type. This implies that when I create a table, I don’t use quotation marks so that the columns can be entered in either capital or lowercase characters in a select statement The decision is entirely personal in this case. However, consistency is important. I like uppercase keywords and PASCAL case for things like column and table names, but it is up to you to define your style.

When selecting only certain columns from the table:

  • Specify each column’s name when selecting multiple columns.
  • Column names must be separated by commas.

For example, the following SELECT statement retrieves particular columns and rows from the given table.

SELECT EmployeeId, Name, LastName, FirstName 
FROM Employee;

This query, using the table provided, returns:

Graphical user interface, text Description automatically generated with medium confidence

Sorting data: ORDER BY

The ORDER BY clause is used to sort the result set in ascending or descending order. When you execute a query with no ORDER BY clause, the order of the output is not guaranteed to be in any order. 

For example, assume you wish to sort the data from lowest to highest date of birth.

SELECT  *  
FROM Employee 
ORDER BY DOB;

This returns the following, note that the data in the DOB column is sorted when the results are returned:

Graphical user interface, table Description automatically generated

By default, ORDER BY sorts the rows in ascending order. Although it is the default, you may optionally add ASC to the end of the ORDER BY clause to explicitly state the sort is ascending. By adding DESC at the end of the ORDER BY clause, you can instruct SQL to return results sorted by that column in descending order (For numbers 100 to 1 and letters Z to A).

As a quick example, if you want to sort the data from highest to lowest date of birth, add DESC as a suffix to DOB in the ORDER BY clause.

SELECT *  
FROM Employee 
ORDER BY DOB DESC;

Now you can see the DOB data goes from most recent to oldest data:

Graphical user interface, table Description automatically generated with medium confidence

Sorting by Multiple Columns:

You can use more than one sort of level to order your data. The primary sort order is defined by the first field name, the secondary sort the second, and so on. You simply add more columns to the ORDER BY clause. Each column may be ascending or descending, as you wish.

SELECT Column_Name1, Column_Name2, Column_Name3 
FROM Tablename 
ORDER BY Column_Name1 <desc>, Column_Name2 <desc>, 
         Column_Name3 <desc>;

For example, you may sort your data by salary and then by date of birth within salary:

SELECT * 
FROM Employee 
ORDER BY Salary DESC, DOB DESC;

There are no duplicated values in our dataset, but this is the output.

Graphical user interface, application Description automatically generated

Filtering rows from the output

The SQL SELECT statement’s WHERE clause specifies which rows to (or not to) return from your table or view by filtering rows based on a given condition.

When referring to literal character values in the WHERE clause, one must put the values in single quotes, for example, DEPARTMENT='Sales'; Other datatypes have different rules for how they are represented in code. For example, numeric values should not be surrounded by quotations.

This is the basic syntax:

SELECT <Column Name List> 
FROM   Tablename 
WHERE  <Comparison Expression>
ORDER BY Column_Name <desc>;

The <comparison expression> in the WHERE clause can most any expression returning a Boolean value. For example, you might compare a column value to a literal (Salary = 10000), a column value to another column (CurrentSalary = StartingSalary), or even if a column value has a NULL value (Salary IS NULL). A NULL value generally means that a value is unknown, in that you don’t have the value.

For comparing two values, most comparison operators can be used with a WHERE clause:

Operator

Description

IN

Equal to any item on a list

NOT IN

Not equal to any item on a list

AND

All conditions are true

OR

Any Condition is true

=

Equal

<>

Not equal

>

Greater than

<

Less than

>=

Greater than or equal

<=

Less than or equal

BETWEEN

Between a range

LIKE

Search for a pattern

IS [NOT] NULL

Checks to see if the column value IS NULL

The WHERE clause may also be quite complex depending on the necessary criteria, something that I will cover in a later article.

WHERE Clause Examples

In these next subsections, I will give a few examples of WHERE clauses using different comparison operators.

= (Equal) Comparison Operator

The most common comparison operator is =. It simply is used to compare that two values are equal. For example:

SELECT  *  
FROM Employee 
WHERE Department ='Sales';

This returns the following, where the employee is in the Sales department:

Table Description automatically generated

<> Not equal Comparison Operator

The following query shows all employees from Department Sales.

SELECT  *  
FROM Employee 
WHERE DEPARTMENT <> 'Sales';

This returns:

Graphical user interface, application, table Description automatically generated

There are also comparison operators for > (Greater than), < (Less than), >= (Greater than equal to), <= (Less than equal to), and more that work in a similar way.

IN Comparison Operator

The following query returns all Employee rows with EmployeeId values in the range of ‘1001’,1002, or ‘1003’.

SELECT * 
FROM Employee 
WHERE EmployeeId IN ('1001',1002,'1003');

This returns:

Graphical user interface, application Description automatically generated

If you want the rows that are not in a certain range, you need to use NOT IN. For example, the following query returns all Employee rows with EmployeeId values, not in the range of ‘1001’,1002, or ‘1003’.

SELECT *
FROM Employee 
WHERE EmployeeId NOT IN ('1001',1002,'1003');

This returns the other rows in the table:

Graphical user interface Description automatically generated with medium confidence

Note: be slightly careful with the NOT IN operator when NULL values could be involved. Column NOT IN (NULL, 1, 2) will never return any rows. NULL comparisons return NULL, and only rows with a TRUE comparison will be returned.

Graphical user interface, table Description automatically generated

AND Boolean Operator

Boolean operators are used to create more complex filters by tying 2 or more conditions together. For example, say you need to find all employees from the “Sales” Department with the last name “Grant”.

The two conditions are equality operations, and then we tie them together with AND:

SELECT  *
FROM Employee 
WHERE Department ='Sales' 
  AND LastName='Grant';

The result is:

OR Operator

Much like and, but in this case, we want to find where any condition is met. For example, the following query finds all employees from the “Sales” Department or last name is “Grant”

SELECT  *  
FROM Employee 
WHERE DEPARTMENT='Sales' 
   OR LastName= 'Grant';

This returns:

Graphical user interface, table Description automatically generated

It should be noted that when using AND and OR Boolean expression you need to take care when combining them. Use parenthesis to group together items. For example, if you want all employees from the “Sales” Department with the last name “Grant” as well as all employees not in the “Sales” Department, you will use the following:

WHERE (Department ='Sales' 
       AND LastName='Grant')
    OR (Department <> 'Sales')

Between Comparison Operator

The SQL BETWEEN operator is used to filter data based on a range of values. It allows you to select rows from a table where a column’s value falls within a specified range.

Note that the BETWEEN operator is inclusive, meaning it includes both the lower and upper bounds in the range. The following query returns all employees whose salaries are between $50000 and $70000.

SELECT  *  
FROM Employee 
WHERE Salary BETWEEN 50000 And 70000;

This returns:

Graphical user interface, table Description automatically generated

In the output you can see that the two rows with 50000 and 70000 are in the output. If you want to exclude the bounds, you need to be specific in your comparison. For example, the previous BETWEEN expression could be re-written:

WHERE Salary >= 50000 AND Salary <=70000;

If you didn’t want the endpoints, you could rewrite it as:

WHERE Salary > 50000 AND Salary <70000;

And you may need to vary that based on exactly what you are trying to achieve. Some people do not like to use BETWEEN because it isn’t as expressive as using individual comparison operators.

The LIKE Comparison Operator

A very important operator that I want to introduce is the LIKE operator. It lets you find more complex matches using simple comparison operators.

The LIKE operator does a pattern match comparison, which means it compares a string value to a pattern string that contains wildcard characters.

Wildcards can be defined using a “%” or “_” symbol both before and after the pattern

In Oracle SQL, the escape character can be used in a LIKE statement to escape special characters and match their literal value instead of their special meaning. The escape character is specified using the ESCAPE clause, and its default value is the backslash (\) character. For more information about escape character or wild cards please refer to the Oracle link

Note: Oracle also supports a regular expressions LIKE operator too. For more information about this, check out this article.

The percent sign (%) represents many, multiple, or zero characters, while the underscore symbol (_) one and only one value.

For example. the SQL query below will return employees whose first names begin with the letter ‘A’:

SELECT  *  
FROM Employee 
WHERE Name like 'A%';

This returns the following:

Graphical user interface Description automatically generated with low confidence

The SQL query below will return employees whose first names end with the letter ‘t’:

SELECT  *  
FROM Employee 
WHERE Name like '%t';

Which you can see in the results:

Table Description automatically generated with medium confidence

The SQL query below will return employees whose first names include the letter ‘C’:

SELECT *
FROM Employee 
WERE name like '%C%';

This returns the following:

Graphical user interface, application Description automatically generated

Note: Be cautious when using LIKE expressions with leading wildcard values because normal indexes may not be particularly beneficial due to the way indexes are structured and prevent efficient index utilization that uses a leading wildcard. As a result, LIKE expressions with leading wildcards (for example, ‘%list’) should be avoided where possible.

Finally, the underscore symbol (_) specifies a single character. Hence, the SQL query below will return employees with the letter “l” in the second position in their first names.

SELECT *
FROM   Employee 
WHERE  name like '_l%';

This returns the following:

Limiting the number of Rows in the output

It is sometimes a good idea or a requirement to display only a certain number of rows from a query. This can help improve performance when working with large tables containing millions of rows of data.

For instance, you may be creating a search application but just want to display a portion of the results. If your search query returns hundreds of rows but you just want to display ten at a time, you would use limit clauses to narrow down your set of results.

Another example would be if you wanted to show the top 10 or 20 highest-paid people from the employee table when your result set returned a thousand rows. The following clauses can be used with the Select statement to limit the number of rows.

FETCH FIRST or FETCH NEXT:

  • Specify the NEXT or FIRST row or rows to be returned.
  • Specify the number of rows to be returned.

The integer literal value must be 1 or greater for the fetch first clause. If the literal is missing, the value defaults to 1. This is the base syntax:

SELECT ColumnName1, ColumnName2, ColumnNameN 
FROM Tablename 
ORDER BY ColumnName1 FETCH FIRST/NEXT number ROWS/ROWS ONLY;

The ORDER BY clause is not required here, but it may be helpful if you want to control the order in which the data is returned. This is especially important when retrieving large datasets.

The following SELECT statement returns the first row from the query of the employee table, sorted by the EmployeeId column.

SELECT EmployeeId, Name, LastName, FirstName  
FROM Employee 
ORDER BY EmployeeId FETCH FIRST 1 ROW ONLY;

The result is the one row:

Next, the following SELECT statement returns the first 3 rows from the employee table, sorted by the EmployeeId columns:

SELECT EmployeeId, Name, LastName, FirstName  
FROM Employee 
ORDER BY EmployeeId FETCH FIRST 3 ROWS ONLY;

Which returns:

Table Description automatically generated

In the next example, the SELECT statement returns the next 2 rows and skips the first-row employee table, sorted by the EmployeeId columns.

SELECT EmployeeId, Name, LastName, FirstName, Department, Dob, Salary  
FROM Employee 
ORDER BY EmployeeId FETCH NEXT 2 ROWS ONLY;

In the result, you can see that this is still just the first 2 rows. The value of this will become more obvious in the next sections.

Graphical user interface, application Description automatically generated

OFFSET:

The OFFSET clause allows you to skip the first N rows in a result set before returning any rows.

The value of the integer literal (or the dynamic parameter?) for the result offset clause must be either 0 (default if no clause is specified) or positive. If the number of rows is more than the number of rows in the main result set, no rows are returned.

SELECT ColumnName1, ColumnName2, ColumnName N 
FROM Tablename 
ORDER BY ColumnName1 OFFSET number ROWS/ROWS;

The following SELECT statement skips the first two rows and returns the remaining rows sorted by the EmployeeId columns.

SELECT EmployeeId, Name, LastName, FirstName, 
       Department, Dob, Salary 
FROM Employee 
ORDER BY EmployeeId OFFSET  2 ROWS;

Now you can see in the following rows that 1001 and 1002 are not in the output, since they were the first two rows based on the sort order:

Graphical user interface, application, table Description automatically generated

Using OFFSET together with NEXT/FIRST

The OFFSET clause may be used in combination with the NEXT or FIRST clauses to restrict the number of rows returned in the result set.

For example, the following SQL skips the first employee, employees are ordered by lowest salary to highest salary, and returns the next two employees.

SELECT EmployeeId, Name, LastName, FirstName, Department, 
        Dob, Salary  
FROM Employee 
ORDER BY SALARY OFFSET  1 Rows FETCH NEXT 2 ROWS ONLY ;

Result:

A picture containing application Description automatically generated

Eliminate duplicates using DISTINCT:

The SELECT command retrieves data from table columns. But what if we only want unique data? A column in a database frequently has many duplicate values, thus there are instances when you just want to show the unique values.

For example, a business user may require a list of the unique countries of birth of all employees of a company to assess the organization’s diversity. Because many employees may have the same birth country, we may prefer a separate count of employees by country of birth rather than a total count of employees. In this case, we can use DISTINCT keyword with a SELECT statement.

The DISTINCT keyword specifies that only distinct (unique) data should be returned. Using DISTINCT will remove duplicates from the results table.

SELECT DISTINCT  ColumnName 
FROM Tablename;

The following SELECT statement retrieves unique Department values from the Employee table. There are several employees with the same department, and you as a business user may require a distinct list of departments where employees work.

SELECT DISTINCT Department 
FROM Employee;

Graphical user interface, text, application Description automatically generated

While it is beyond this introduction to the SELECT statement topic, beware of using DISTINCT to cover duplicated data that you don’t understand. When querying more than one table it often is used to hide issues that are either a problem for the performance or correctness of a query.

Grouping Data for Aggregation

The GROUP BY clause in SQL is used to group rows of data in a result set based on the values in one or more columns. The purpose of using the GROUP BY clause is to aggregate data and obtain summary information.

SELECT fieldname1, fieldname2, ... fieldname_n,   
       aggregate_function (aggregate_fieldname)  
FROM tables  
WHERE conditions  
GROUP BY fieldname1, fieldname2, ... fieldname_n;

The aggregate function (aggregate fieldname) represents an the aggregate function that you want to apply to the data, such as SUM, AVG, MIN, MAX, or COUNT. This function will operate on the values in the aggregate fieldname column.

The data will be formed into groups based on the columns in the GROUP BY clause. The values that are not in the GROUP BY clause then are collapsed into scalar values by the aggregate function. Rows with identical values in the grouping columns are grouped. In the query result, each group is interpreted as a single row and aggregate functions (like SUM, MIN, MAX) can be applied to the results For example, if the grouping had three rows with the same value, you could do COUNT(*) as an aggregate function and it would return 3.

GROUP BY is an optional part of a query. It goes after the WHERE clause or the FROM clause if the WHERE clause is not needed.

For instance, you want to know the total salary of a department. You should use the SUM aggregate function and group the data by departments.

SELECT Department ,Sum(Salary) FROM Employee  GROUP BY Department;

In our data set, this will return:

Table Description automatically generated

Filtering Groups of Data

The HAVING clause in SQL is used in conjunction with the GROUP BY clause to filter groups based on a specific condition. The HAVING clause operates on the results of the aggregate function, whereas the WHERE” clause operates on individual rows.

SELECT fieldname1, fieldname2, ... fieldname_n,   
       aggregate_function (aggregate_fieldname)  
FROM tables  
WHERE conditions  
GROUP BY fieldname1, fieldname2, ... fieldname_n 
HAVING aggregate_condition;

The aggregate condition is the condition that you want to apply to the groups of data, using the results of the aggregate function. For example, you could specify HAVING AVG(fieldname2) > value to only show the groups where the average of fieldname2 is greater than a certain value.

For an example, the following query returns the average salary for all departments that have an average over 61000 using the HAVING clause.

SELECT Department, AVG(salary)
FROM Employee
GROUP BY Department HAVING AVG(Salary) > 61000;

The result is:

Table Description automatically generated with medium confidence

Summary

In this introduction to the SELECT statement in Oracle, we have looked at how to query a single table, return only certain columns, put that data into a specified order, filter it down to a set of (if desired, distinct) rows, and then group that data and do aggregates.

It is a lot in one introduction, but the SELECT statement is the one statement that pretty much every Oracle user of any level will use. In the future, I will look at querying multiple tables at the same time, as well as how to create and remove data from a database.

The post The SELECT Statement in Oracle appeared first on Simple Talk.



from Simple Talk https://ift.tt/5nhEOdA
via

Tuesday, March 14, 2023

Are PostgreSQL memory parameters magic?

Configuration parameters are the most mythical creatures in the world of PostgreSQL.

Ordinary PostgreSQL users often do not know that PostgreSQL configuration parameters exist, let alone what they are and what they mean. There is a good reason for such ignorance since, in real life, ordinary users don’t have any say in how these parameters are set. Configuration parameters are set not just for a database but for the whole instance, which may have multiple databases, so any individual user will get the same as others get. To be completely transparent, in some cases, the said ordinary users can specify some parameters just for their own uses, but let’s hold our horses for now.

There are over three hundred PostgreSQL configuration parameters, so no wonder that even experienced DBAs often do not know what each of these parameters does. That is perfectly fine; however, there is a widespread belief that somewhere, in the secret vaults of many consulting companies, there is a treasure chest of perfect PostgreSQL parameter settings.

When the users start to complain that “everything is slow” or nightly backups finish in broad daylight, everybody around screams that “the database server should be optimized!” Many administrators often assume that as soon as we choose the correct values for parameters and restart the database instance, all the world problems will be solved.

Indeed, we all hope to be able to solve all problems at once; however, although some parameter tuning can indeed improve the database performance, we are usually talking about 10%, 20%, and in rare cases, up to 50% performance improvement if some parameters are set poorly. That might sound like impressive numbers, but individual query optimization routinely makes queries run several times faster, in some cases, ten or more times faster, and restructuring applications can improve overall system performance by hundreds of times!

Maybe not magic, but we can’t ignore config parameters, right?

It’s important to at least know what the most critical configuration parameters can do, and it doesn’t hurt to explore them all. However, believing that there are some magical “correct” values that exist is dangerous. If it were the case, these parameters would already be set up correctly in the default configuration, and nobody would ever have to change the values.

In truth, there is no such thing as a “set it and forget it” configuration for PostgreSQL because different users have different needs. If there were they would be on the first page of the PostgreSQL manual, and companies would no longer have to pay top dollar to consultants. While some tried and true formulas can be used for the initial setup, parameters should be adjusted to work for a specific environment and customer needs, based on what kind of load they are putting on a server.

Furthermore, parameters ought to be re-evaluated any time we switch the server configuration, hardware, or to a new version of PostgreSQL.

In short, nothing is set in stone.

In the remaining part of the article, let’s look at some important configuration parameters and the myths surrounding them.

Helping PostgreSQL play nicely with its neighbors

PostgreSQL is a resource-greedy system. It will use all available resources and there is no way to tell PostgreSQL, “please, use just one CPU.” Some parameters can be used as loose guidelines for the query planner, but their influence is limited; for example, we can increase the cost of some operations or algorithms, which can have an indirect impact on resources usage. Such behavior may cause problems if you choose to place multiple PostgreSQL clusters on one machine and multiple databases on one cluster. Each of these instances would be unaware that is shares the hardware with others and would attempt to grab (almost) all resources available on the host.

As an example, correctly setting work_mem is a necessary task for any PostgreSQL workload. It’s common for DBAs to use online “parameters calculators”, not realizing that these tools assume one PostgreSQL instance per host with one database on the instance. This becomes a problem if you have more than one PostgreSQL instance per host. For example, if the host has 96GB of RAM with four instances of PostgreSQL running, we could assume that each instance can be limited to 24GB of RAM. That is fine for initial calculations, but it is important to remember that you can’t tell PostgreSQL, “Do not take more work memory, it’s not yours!”

Moreover, when you set up the first PostgreSQL instance on a host, it might be one instance, and all formulas will work. But if later, you decide to set up one additional instances on the same host, you most likely won’t remember that for the first instance, parameters were set as if this instance existed on that host solo. Because of that, it is probably unlikely that you would stop this first instance to reconfigure parameters.

The same applies to the development instances and perhaps even more to testing/staging instances. It’s important to remember that you can’t adequately test application performance on a database that resides in a multi-tenant environment. Placing multiple databases on one cluster (even testing/staging) might result in improper permissions settings (users and roles are created on the cluster level rather than the database level).

Memory, connections, etc.

Memory allocation parameters are the most mythical of all PostgreSQL configuration parameters. Many recommendations and formulas, which can be found on the Internet, were issued many years and many PostgreSQL versions ago, and many of them were never revisited since.

Most conventional recommendations are either wrong or can be used only as a first approximation and tuned later. Don’t miss that last part. No matter what values you set for parameters, it will be important to watch performance and resource utilization and adjust if needed.

shared_buffers

The data stored in a PostgreSQL database has to be read from a hard disk drive to main memory before anybody can use it. The memory area which is allocated for this purpose is called shared memory buffers. This parameter sets the number of shared memory buffers used by the database server. The historical limit of 64 GB is mythical and goes back to older versions of Linux.

This is one of the few memory-related parameters which PostgreSQL uses at its face value, meaning that it sets the hard limit for shared buffers. The only actual limitation to this value is that after subtracting this value from total RAM, there should be enough RAM left for work_mem (discussed earlier).

Note: Changing this parameter requires an instance restart.

Recommendation: start from 25% of RAM and increase until cache_hit_ratio is close to 90%

effective_cache_size

This parameter is advisory. It does not reserve any memory, and PostgreSQL uses it for query planning purposes only. It indicates how much memory the operating system has available for caching data (so it includes memory cache, disk cache, filesystem cache, etc.) The way the query planner uses it is not straightforward, but the higher it is defined, the higher the chances of using indexes rather than a sequential scan.

Recommendation 75% RAM is usually recommended but not required (and this number is not related to the shared_buffers value)

max_connections

This parameter sets the maximum number of concurrent connections to the PostgreSQL instance, which can be handled simultaneously. This is a hard limit; if the maximum number of connections is reached, the system will become non-responsive. No users except for a superuser will be allowed to connect. This situation will persist until the superuser kills some connections. Changing this parameter requires a system restart. You might wonder why this limit is necessary, and if it can’t be changed on the fly, why not set it as high as possible so that we never run into these problems?

Too many connections are undesirable in any database because each connection takes up additional resources, even when idle. On the application level, this problem is addressed by setting up an application connection pool so that application users do not initiate new database connections but instead use one of the already opened connections from the available pool. If we set this value really high, the system may become slow and non-responsive because there won’t be enough resources for all connections. In addition, there are some internal limitations in the PostgreSQL kernel itself, which makes it undesirable to have more than several hundred connections at any given moment.

Now that we have described many of the problems that occur when there are too many connections, we should note that these horror stories are at least partially mythical as well. If there are enough hardware resources available on the host, even several thousand max_connections may work perfectly fine.

Recommendation: Start from several hundred, observe system behavior, and adjust accordingly.

work_mem

The work_mem setting controls the amount of memory that can be used per query operation node and is generally used for sorting data and hash tables. This is also a hard limit, meaning that this is the maximum size of memory PostgreSQL will allocate to any query node.

Any hash operation that requires more than this amount of memory will resort to swapping to disk and will therefore take longer to complete.

A well-known formula suggests dividing 25% of the total system memory by max_connections.

Therefore, a decrease in max_connections will allow for a higher value of work_mem. Note that in this case, like in many others, it is assumed that the host has only one database, so you have to be mindful when assigning the value for this parameter. Remember that PostgreSQL won’t perform any calculations to check whether your settings make sense. Everybody might be happy until the next session cannot obtain the necessary portion of RAM from the operating system and will receive an out-of-memory error.

Fortunately, work_mem is one of PostgreSQL parameters which can be set dynamically, for a specific session. Thereby, a possible solution could be to set the work_mem dynamically from the application. Suppose it is known that a particular query will be sorting a large data set. In that case, it can be advantageous to increase the work_mem of that individual query (being careful not to over-allocate).

For example, if the session requires 200 GB for work_mem, you can run the following command:

set work_mem = '200GB';

This would set the session’s work_mem to a new value and allow subsequent queries within that session to utilize more memory for sorting or hashing. To return to the standard value, run the following:

reset work_mem;

maintenance_work_mem

This parameter determines the maximum amount of memory used for maintenance operations like VACUUM, CREATE INDEX, ALTER TABLE ADD FOREIGN KEY, and data-loading operations (eg. COPY). These may increase the I/O on the database servers while performing such activities, so allocating more memory to them may lead to these operations finishing more quickly. There is a formula to calculate this value as well, but we will discuss this parameter in connection with the PostgreSQL VACCUM process.

Is that all of the memory parameters?

In this article, I have covered a few of the most important parameters surrounding PostgreSQL memory tuning. If you want to view all of the parameters that are available for PostgreSQL memory tuning, you can view more here in the PostgreSQL documentation.

Was this article helpful? Would you like to keep exploring the myths and reality of PostgreSQL configuration parameters? Let me know in the comments!

 

The post Are PostgreSQL memory parameters magic? appeared first on Simple Talk.



from Simple Talk https://ift.tt/hqtJeBE
via

Friday, March 10, 2023

Build a Better WordPress Archives Page Using MySQL

I recently wrote about a way to generate visual, interactive calendars in HTML by combining a calendar table with data from an events table (part 1 and part 2). This technique could be used to overlay any type of data onto calendars, but my specific goal was to make the monthly archives page on my blog a little less boring.

I started with SQL Server because that’s what I know, but I knew that wouldn’t be my final solution. Like many of you I’m sure, my blog runs on WordPress and MySQL. To make matters worse, my host is stuck on MySQL 5.7, which is missing some major conveniences I’ve been spoiled with in SQL Server, and that have been added to MySQL in the meantime – most notably, common table expressions (CTEs) and ROW_NUMBER().

In this post, I’ll show how I worked around that. But let’s start from the beginning, by starting from the end.

The End Goal

Think about the page (or sidebar) where your blog’s monthly archives (or any monthly breakdown of events, really) are typically represented in this simple way:

Archives
January 2023 (3)
December 2022 (2)
November 2022 (5)
…ho hum (ad nauseum)

A while back, I made a change to that page on my site so that each month was represented by a visual calendar. But it was static CSS; every month looked the same, with the only changes being the month name and the clickable number (representing number of posts in that month):

Initial boring calendar design

But my vision was for the month to look accurate, with the first day starting on the right weekday, along with clickable days when blog posts were published (including special highlighting for days with multiple posts), clickable months to take you to an index for the month, and clickable years to take you to an index for that year.

My initial 2-minute sketch looked like this:

Initial calendar sketch

I fine-tuned it in HTML and CSS like this:

Much more appealing and functional calendar design

The HTML is easy enough to generate by hand, if you have a limited calendar and number of events:

HTML structure

But since my blog anthology spans more than 16 years and, presumably, you don’t want to muck with that HTML every month and for every new post you publish, we’ll need some programmatic help to make this automatic.

You’ll notice those aren’t standard HTML elements like <span> and <div> – I made my own because it was much easier to build and debug without extra noise, and also so I wouldn’t have to override any styling applied by templates, plug-ins, and WordPress itself. The <year> element is a grid, set up this way:

year 
  {
    display: grid; 
    grid-template-columns: repeat(auto-fill, 210px);
  }

<month> is just a 210px × 156px, fixed-dimension wrapper around <days>, that fills <year> in a responsive way, thanks to the auto-fill grid. The dimensions are arbitrary, but were meant for the calendar to fill months 6, 4, or 3 wide, depending on browser window size.

month 
  {
    width:  210px;
    height: 156px;
  }

<days> becomes a grid-within-a-grid, which allows 30-pixel wide <day> elements to flow 7 columns wide and up to 6 rows high (since some months that start on a Friday or Saturday actually have 5 Sundays), within their <month> container:

days
  {
    display: grid;
    grid-template-columns: repeat(7, 30px);
    grid-template-rows:    repeat(6, 21px);
  }

Finally, as I described in an earlier post, starting the weekday accurately (e.g. in the right grid column) relies on this ingenious CSS from Zell:

/* for each <days class=d{X}> make {X} the first column */
  days.d1 day:first-child { grid-column: 1; }
  days.d2 day:first-child { grid-column: 2; }
  days.d3 day:first-child { grid-column: 3; }
  days.d4 day:first-child { grid-column: 4; }
  days.d5 day:first-child { grid-column: 5; }
  days.d6 day:first-child { grid-column: 6; }
  days.d7 day:first-child { grid-column: 7; }

No, this isn’t the most responsive design I’ve ever created, because I rely on explicit pixel sizes, but if you view the site on a mobile device, you’ll see these dimensions are adjusted slightly to fill the screen appropriately.

How to Get There

My plan seemed simple: just port the same T-SQL queries I already wrote to MySQL, pull them from a PHP page, and call it a day. But, as hinted earlier, limitations in MySQL 5.7 made me step back. I thought about the things I needed to help me automate HTML generation, and how some would be complicated by the lack of modern language features, and by me being more comfortable writing MySQL queries than PHP code:

  • A calendar table representing all of the dates I would ever need to display:
    • Start from the first day of the first month of my very first post (December 2006)
    • End at the last day of some month in the future
    • For each month, whether it is the first or last month in a (partial!) year
    • For each day, attributes that indicate:
      • Whether it is the first or last day of the month
      • For the first of each month, the weekday it falls on
  • Data from wp_posts for every published post:
    • The date of the post
    • The number of posts published that day
    • Aggregated data for each month
    • Aggregated data for each year

I started with the built-in calendar table that will serve many other purposes down the road. Following at least some of WordPress’ existing naming conventions, I used this syntax to generate 8,432 rows, covering December 2006 (the month of my first post) through the end of 2029:

SET @start = DATE('20061201');
  SET @end   = DATE('20291231');

  CREATE TABLE `wp_calendar`
  SELECT  d     AS TheDate,
    YEAR (d)    AS TheYear,
    MONTH(d)    AS TheMonth,
    DAY  (d)    AS TheDay,

  # which day of week does the month start on?

    CASE   WHEN DAY(d) = 1      
           THEN DAYOFWEEK(d) ELSE NULL END
           AS WeekdayOfFirst,

  # is the current date the last day of the month?

    CASE   WHEN LAST_DAY(d) = d 
           THEN 1 ELSE 0 END
           AS IsLastOfMonth,

  # do we need a closing </year> tag because it is 
  # either the last day of January OR the last day of
  # the current month?

    CASE   WHEN (MONTH(d) = 1 AND LAST_DAY(d) = d)
           OR (LAST_DAY(@start) = d AND MONTH(d) > 1)
           THEN 1 ELSE 0 END 
           AS NeedsClosingYear
  FROM 
  (
    # add a day to every day in the range
    SELECT DATE(DATE_ADD(@start, INTERVAL n-1 DAY)) AS d 
    FROM 
    (
       # loop variable to simulate ROW_NUMBER()
       SELECT (@rn := @rn + 1) AS n 
         FROM       INFORMATION_SCHEMA.COLUMNS AS c1
         CROSS JOIN INFORMATION_SCHEMA.COLUMNS AS c2
         CROSS JOIN (SELECT @rn := 0)          AS rn
         LIMIT 10980   # more than 30 years!
    ) AS Numbers
  ) AS Days WHERE d <= @end;

You can experiment with the contents of such a table in this db<>fiddle, but keep in mind this may generate a forward-compatibility warning in some versions.

I rely on INFORMATION_SCHEMA having enough columns in a WordPress installation, and this gets me well beyond the needed 8K+ rows. If you don’t have enough rows where you’re implementing this, you can cross join the view again. In MySQL 8.0, I probably would have used a recursive CTE to generate a series of days (though I would have to manage cte_max_recursion_depth to get more than 1,000 rows). This would avoid cross joins, identifying the number of days required, and pesky loop variables that might produce unwanted warnings.

WITH RECURSIVE Days(d)
  AS
  (
    SELECT @start
    UNION ALL
    SELECT DATE_ADD(d, INTERVAL 1 DAY)
      FROM Days WHERE d < @end
  )
  ...

…but, I don’t have that luxury on my site today.

I moved on to creating multiple stacked views to aggregate valid post data by day, then by month, and then by year. I did it this way to prevent the approach from becoming overly complicated in one giant query and to avoid repeating expressions multiple times at the same level. And also because I know I will be able to find other uses for some of these individual views.

First, a view to aggregate posts by day (and filter out drafts and other post types from all subsequent views):

CREATE VIEW v_post_days
  AS
    SELECT DATE(post_date) AS TheDate,
           COUNT(*)        AS DayCount,
           CONCAT('/', YEAR(post_date), 
                  '/', MONTH(post_date), 
                  '/', DAY(post_date), '/') AS Url
    FROM `wp_posts`
    WHERE post_type   = 'post'
      AND post_status = 'publish'
    GROUP BY DATE(post_date);

Then we can use that view to aggregate by month:

CREATE VIEW v_post_months
  AS
    # first of month, even for leap years:
    SELECT m + INTERVAL 1 DAY - INTERVAL 1 MONTH 
                        AS FirstOfMonth,
           m            AS LastOfMonth,
           YEAR(m)      AS TheYear,
           MONTH(m)     AS TheMonth,
           MonthCount,
           CONCAT('/', YEAR(m), '/', MONTH(m), '/') AS Url
         FROM
         (
           SELECT LAST_DAY(TheDate) AS m,
                  SUM(DayCount)     AS MonthCount
           FROM v_post_days
           GROUP BY LAST_DAY(TheDate)
         ) AS x;

And finally by year:

CREATE VIEW v_post_years
  AS
    SELECT TheYear, 
           SUM(MonthCount)           AS YearCount,
           CONCAT('/', TheYear, '/') AS Url
    FROM v_post_months
    GROUP BY TheYear;

Putting it All Together

To combine our aggregated post data with the overall calendar table, we can select from the latter and outer join to the views. I expose a bunch of additional columns here because many will be used to either inject directly into the output HTML or help with conditional logic to decide what CSS classes to add and whether to end an HTML element:

ALTER VIEW v_post_calendar
  AS
    SELECT cal.TheDate,
 
      # for partial years, we need <year>
      CASE WHEN y.TheYear IS NOT NULL THEN 1
        ELSE 0 END AS NeedsOpeningYear,
 
      # year info
      y.Url AS YearUrl,
      cal.TheYear,
      y.YearCount,
 
      # month info
      m.Url AS MonthUrl,
      MONTHNAME(cal.TheDate) AS MonthName,
      cal.TheMonth,
      m.MonthCount,
 
      # day info
      cal.WeekdayOfFirst,
      d.Url AS DayUrl,
      d.DayCount,
      cal.TheDay,
 
      cal.IsLastOfMonth,     # need a closing </month>?
      cal.NeedsClosingYear   # need a closing </year>?
    FROM `wp_calendar` AS cal
    LEFT OUTER JOIN v_post_days AS d
      ON cal.TheDate = d.TheDate
    LEFT OUTER JOIN v_post_months AS m
      ON cal.TheDate IN (m.FirstOfMonth, m.LastOfMonth)
      
    # need to know if it's the last month in the
    # current year, especially in the case where
    # there are no posts yet for the current month
    LEFT OUTER JOIN v_post_years AS y
      ON cal.TheDay = 1 
      AND cal.TheYear = y.TheYear
      AND
      (
          cal.TheMonth = 12 
          OR LAST_DAY(cal.TheDate) = LAST_DAY(CURDATE())
      )
    # need to stop on the last day of *this* month:
    WHERE cal.TheDate <= LAST_DAY(CURDATE());

The complicated part, of course, is building the final HTML output, which can be a very iterative process to get right – not just when there is a lot of data, but also when there are several edge cases. And when you want the source more legible and easier to troubleshoot, it pays to have additional whitespace peppered in there (like \r, \n, and \t).

CREATE VIEW v_post_calendar_html
  AS
    SELECT TheYear, 
           TheMonth,
           TheDay, 
           CONCAT(OpenYear, OpenMonth, Day, CloseMonth, CloseYear) AS html
    FROM
    (
      SELECT TheYear, 
             TheMonth, 
             TheDay,

        # OpenYear (need to add <year><yearname> etc.):
        CASE WHEN NeedsOpeningYear = 1 
        THEN CONCAT
        (
          '\r\n<yearname>',
          CASE WHEN YearCount > 0 THEN 
            # if any posts in that year, make it a link
            # and display the number of posts:
            CONCAT
            (
              '<a href="', YearUrl, '">', 
              TheYear, '</a> (', YearCount, ')'
            )
            ELSE TheYear END,
          '</yearname>\r\n<year>'
        ) ELSE '' END 
        AS OpenYear,

        # OpenMonth (need to add <month><monthname> etc.):
        CASE WHEN TheDay = 1 
        THEN CONCAT
        (
          '\r\n\t<month>\r\n\t\t<monthname>',
          CASE WHEN MonthCount > 0 THEN
            # if any posts in that month, make it a link
            # and display the number of posts:
            CONCAT
            (
              '<a href="', MonthUrl, '"',
              ' title="', MonthName, ' ', TheYear, '">',
              MonthName, '</a> (', MonthCount, ')'
            )
            ELSE CONCAT('<b>',MonthName,'</b>') END,
          '</monthname>',

          # set the right grid column for the first day:
          '\r\n\t\t<days class="d', WeekdayOfFirst, '">\r\n'
        ) ELSE '' END 
        AS OpenMonth,

        # Day (need one of these for every day in the range)
        CONCAT
        ( 
          '\t\t\t<day', 
          # need styling if the day has posts or is in the future
          CASE WHEN DayCount > 0 OR TheDate > CURDATE()
          THEN CONCAT
          (
            ' class="',
            CASE WHEN DayCount > 0         THEN ' on'     ELSE '' END,
            CASE WHEN DayCount > 1         THEN ' multi'  ELSE '' END,
            CASE WHEN TheDate  > CURDATE() THEN ' future' ELSE '' END,
            '"'
          ) ELSE '' END, 
          '>',
          CASE WHEN DayCount > 0 THEN
          # make the day clickable and title with nicely formatted date
          CONCAT
          (
            '<a href="', DayUrl, '" title="', 
            DATE_FORMAT(TheDate, '%M %D, %Y'),
            '\r\n', DayCount, ' post',
            CASE WHEN DayCount > 1 THEN 's' ELSE '' END,
            '">', TheDay, '</a>'
          )
          ELSE TheDay END, 
          '</day>'
        ) AS Day,
  
        # CloseMonth (every last of the month needs </month>)
        CASE WHEN IsLastOfMonth = 1 
          THEN '\r\n\t\t</days>\r\n\t</month>' 
          ELSE '' END AS CloseMonth,

        # CloseYear (last of each year needs </year>)
        CASE WHEN NeedsClosingYear = 1 
          THEN '\r\n</year>' 
          ELSE '' END AS CloseYear

      FROM v_post_calendar
    ) AS x;

I added a few niceties here, like prettier title attributes for clickable days, and no pluralization bugs for days with one or multiple posts:

Prettier title tag

Again, some of this was much more useful to me while developing than it is for the final output.

Anyway, I’m probably breaking all kinds of tribal coding conventions and best practices when working with MySQL, but I’m okay with that, since this is about the first thing I’ve ever published that wasn’t written in Transact-SQL.

Finally, the PHP that queries the view and renders the HTML is rather simple, because we’ve done all the work in the query. Though it can’t be called from a regular page; you need to do this from a custom page template and have your regular archives page inherit from it:

<?php
    global $wpdb;
    $query = "SELECT html 
                FROM v_post_calendar_html 
                ORDER BY TheYear DESC, TheMonth DESC, TheDay;"; 

    $rs = $wpdb->get_results($query); 

    foreach ($rs as $row): 
      echo $row->html.PHP_EOL;
    endforeach; 
  ?>

And now, because the views automatically return data up to and including the current month, you don’t have to touch this again as months and years roll over, outside of the case where your blog is still running in 2030. Or, maybe, if you unpublish posts from the oldest month and want to stop that month from showing up empty. With my previous solution I had hard-coded the list of years and months, and only pulled the number of posts dynamically from the database, so this is already reducing my workload by a little bit every month.

You can see this in action on sqlblog.org, and view the source to confirm the output is as expected. You can also view the CSS, which I left in the HTML source instead of squirreling it away into a separate CSS file, and didn’t minify it so you could grok it easily. Just right-click the page, choose View Page Source, and search for:

/* Archives page CSS */

Further Enhancements

A couple of enhancements I’ve contemplated but not published, and may cover in a future post:

  • List the post titles in the title tag – currently I just show how many posts are on a given day, but the title(s) could be surfaced by the underlying views in order to display them as well (granted, a title tag isn’t a great place to put a lot of information).
  • Make single-post days redirect right to the post – the archive-by-date-parts page in WordPress defaults to showing a post listing, even in cases where there’s only one post. Seems then having to click on that post is an unnecessary step, and either the direct URL could be put into the calendar in that case, or I could dig into the WordPress code or the theme template and have the destination page check the count and decide what to do. This could work for months and years, too, since any of those slices could contain just a single post.
  • Provide more granular calendars – the underlying views could also group by tag or category, allowing an archives page to present a calendar just for that subset of posts. Showing a calendar for my Bad Habits series, for example, would really highlight when I was very active on Stack Overflow and coming across a lot of terrible stuff there. In multi-author blogs (like this one!), you could make it so users see a visual calendar just for the selected author.

Conclusion

How you might implement this in your own blog will differ, depending on where you’re hosting, what version of MySQL you’re using, and the theme you’ve implemented. But the core concept is the same: build a calendar table, outer join to your events table, and then build the HTML. No more boring, never-ending lists of month names!

The post Build a Better WordPress Archives Page Using MySQL appeared first on Simple Talk.



from Simple Talk https://ift.tt/PJONoBz
via

Wednesday, March 8, 2023

Why a monitoring tool is an essential tool for growing server estates

When I was a DBA involved with the management of a large number of database servers, I didn’t have many third-party tools to help me do my job. For the most part, I relied on scripts that I found or wrote. I enjoyed writing scripts to manage the servers, as it taught me a lot about the internals of SQL Server. Many of these scripts were eventually automated using SQL Server’s agent to run and save data on the different servers so we could review the results, looking for issues.

Some of these tools written over 20 years ago still run to this day. We captured tons of data about everything we wanted to know about the server in case there were issues. Loads and loads of data. We had some processes that would scan that data and send emails when obvious errors occurred, but it was hard to keep synchronized over many different servers.

Over the years, the number of servers and mix of database platforms grew (PostgreSQL, MySQL, for example), but not the number of DBAs, keeping up with the changes in technology and complexities of everything we needed to manage was nearly impossible. The process was basically akin to playing whack-a-mole with the users popping up saying, “My app seems slow,” “I can’t do payroll,” “Why can’t I get to…” and all the fingers would point to the database server. So, we would go to the server and prove them wrong (or occasionally, find that it was the database server’s fault…it happens.)

Over time, as we fixed more and more issues, we grew a great library of scripts to diagnose issues with our SQL Servers, but no matter how complete your script library is, as database platforms get more and more complex, it is harder and harder to keep up. Especially when the average DBA doesn’t have 40 hours a week to only sit and keep up with performance problems.

As we continue into the era of supporting more and more database platforms in our data estates, self-monitoring goes from being a very difficult task to a truly daunting task. I am personally advanced at diagnosing Microsoft SQL Server performance issues, but when that PostgreSQL server gets added, I just have to hope nothing goes wrong for a few years while I learn.

Enter monitoring tools

A monitoring tool can help DBAs keep track of things like drive space, licensing, and version end-of-support that can aid in budget discussions. Using baselining features can show whether the server is performing the same or worse over time. And using more advanced software than the average DBA has time for, it can coalesce data from multiple sources and tell you the complete picture of what an issue may be. Best of all, a software company offering monitoring tools will almost certainly keep up with the changes to the various performance monitoring options that all the RDBMS vendors support over time as new versions are released.

Monitoring tools help you swivel from being reactive to being proactive because they can watch as many servers as you license them to, 24/7, and tell you where you might be going wrong. That is right, “might”.

Every data estate is different, and monitoring tools don’t know what all your organization does. Highlighting issues that might be a problem allows you to be proactive. Your server is at 98% CPU usage at this time every day. Here are the processes and queries running at that time. Then you decide, is it a query, is it hardware, or is it that an executable name Asteroids.exe starts up every day at this time for some reason and uses a lot of extra CPU?

A necessity, not a luxury

Unfortunately, some shops see buying tools to monitor database servers as a waste of resources when they are already paying the salaries of their DBA staff. This is like a construction worker who can’t get a bulldozer to do some landscaping because “I already pay that construction worker’s salary.” Sure, the worker has a shovel and can get to it, but that bulldozer can do in one hour what the person can do in 3 weeks. And the bulldozer is still useless without the person driving it.

Most organizations don’t have enough DBAs to start with, and hence their job turns into that aforementioned Whack-a-Mole game just fixing whatever pops up next. But if you have ever played Whack-a-Mole, can you imagine how much easier if you knew where to whack before you saw that pesky critter staring you in the face? Augmenting your database management staff with proper monitoring tools will help them react to many issues before they are even noticed. Any time saved without customers not saying, “why can’t I do my job?” or “why can’t I spend my money with you?” is worth a lot more than a monitoring tool will ever cost.

If you liked this article, you might also like this Redgate product article:  How to convince your boss you need SQL Server monitoring.

 

The post Why a monitoring tool is an essential tool for growing server estates appeared first on Simple Talk.



from Simple Talk https://ift.tt/az7cSNC
via

Monday, March 6, 2023

Optional Code in T-SQL Scripts using SQLCMD

When you are writing T-SQL scripts to save away, for example one to create a new database, there are often optional bits of code you need to run sometimes, and not others.

In the creating a database script, there are quite a few parameters you will want as part of your script. The database name, the settings, whether or not to drop the database or not. Built into SQL Server Management Studio is a cool tool called SQLCMD mode. Scripts using this mode get a few scripting tools that are really useful. These tools allow you to do things like insert other script files, set environment variables, and one I particularly like, make sure you don’t accidentally execute a script if no code is highlighted using EXIT to start your script ().

Where it is really lacking is in the area of control of flow language. In this blog I am going to share a few techniques I have used to get around this when building scripts that need to optionally execute different bits of code.

If you are not quite sure what it is, back in 2013, Robert Sheldon wrote this piece on SQLCMD that covers the basics and honestly I have never used a lot of the functionality that is a part of SQLCMD and not a lot has changed over the years with it. But it serves a useful and important place when writing reusable scripts.

General Usage

For the most part when I am building a script, it starts out with one or more :SETVAR commands to make the script reusable. For example, in my standard database create script, it has a lot of variables like the following:

:SETVAR DatabaseName ArticleTest
:SETVAR PrimaryFileGroupSize 10GB
:SETVAR PrimaryFileGroupMaxSize 20GB
:SETVAR PrimaryFileGroupFileGrowth 2GB
:SETVAR PrimaryFileGroupDirectoryOverride "NONE"
:SETVAR ReadCommittedSnapship ON
:SETVAR AllowSnapshotIsolation OFF
:SETVAR QueryStore ON
:SETVAR AcceleratedDatabaseRecovery ON
:SETVAR RecoveryModel SIMPLE

These variables get used in the following manner:

ALTER DATABASE [$(DatabaseName)] 
       SET RECOVERY $(RecoveryModel);

From there I set all the settings and down in the code it fills these variables into the blanks in my scripts. When a task is repetitive as many of them are, this technique lets me just fill in the blanks. 

Some tasks, however similar each time is, have optional code to run. Like a memory optimized filegroup, or simpler to show, something like whether to execute a DROP DATABASEstatement. In the next few examples, I will show you three ways I often use SQLCMD to do something like skipping a command.

Put control of flow code into the :SETVAR command

This is one that I honestly just realized existed as I wrote this. It assume that it has always seemed so outlandish that I didn’t think it would work. (This provides yet another example of why writing is educational for the write too. I try crazy stuff to make sure I am right!).

For example, say you wanted to optionally run all a certain set of code. You can do the following:

:SETVAR test "IF 1=2"

$(Test)
SELECT 'Hi';
GO

Execute this code, and nothing will happen. Change it to IF 1=1, and you will see ‘Hi’ returned. So, any code you can press into the variable you can use. You can even do multiline code if you need it. You just need to have the first double quotes (“) on the line with :SETVAR.

:SETVAR test "
IF 1=2
  SELECT 'Hi';
 ELSE
  SELECT 'Bye'";

$(Test)

Executed, that will currently return ‘Bye’.

For the DROP DATABASE example, you could do:

:SETVAR DatabaseName ArticleTest

--create a boolean conditional expression
:SETVAR AllowDropDatabase "IF 1=1" 

$(AllowDropDatabase)
SELECT 'I would execute DROP DATABASE $(DatabaseName);'

This returns: 'I would execute DROP DATABASE ArticleTest;' Change the variable value to 1=2 and nothing will be returned.

Use in T-SQL Control of flow Statements

A lot of time, it is easier to just use a value in your code to handle the task of making a section work, likely because you already have some T-SQL control of flow language in your code. For example, you might have code that looks like:

IF EXISTS (SELECT * 
           FROM sys.databases 
           WHERE name = '$(DatabaseName)')

To this you might just add: AND 'Yes' = '$(AllowDropDatabase)‘

So now we might rewrite the optional database dropping code as:

:SETVAR DatabaseName ArticleTest

--anything other than Yes will fail
:SETVAR AllowDropDatabase "NO" 

IF EXISTS (SELECT * 
           FROM  sys.databases 
           WHERE name = '$(DatabaseName)'
             AND 'Yes' = '$(AllowDropDatabase)')
SELECT 'I would execute DROP DATABASE $(DatabaseName);';

Of course this won’t return anything because the database doesn’t exist.

In my real scripts, I have lots of statements like the following. I set the variable to DEFAULT or the name of a valid recovery model. :

:SETVAR RecoveryModel DEFAULT

IF '$(RecoveryModel)' COLLATE DatabaseDefault  
                     <> 'DEFAULT' COLLATE DatabaseDefault
   ALTER DATABASE [$(DatabaseName)] 
            SET RECOVERY $(RecoveryModel);

So, the user can set the value to a specific value, or just take the default.

Commenting Out Code

One of the tricks I probably use the most is optionally commenting out code. So just create a :SETVAR variable command that includes either a variable that contains “--” or two variables, one that represents “/*” and another that does “*/” to surround a lot of code.

For this example using the line level comments, it would look like this (you could use the $(AllowDropDatabase) variable over and over for more than two lines.)

:SETVAR DatabaseName ArticleTest

--Use "--" to disallow, and "" to allow
:SETVAR AllowDropDatabase "--" 

$(AllowDropDatabase)DROP DATABASE $(DatabaseName);
$(AllowDropDatabase)GO

If you want to comment entire blocks of code:

:SETVAR DatabaseName ArticleTest

--Use "/*" and "*/" to not execute code. "" for both to
:SETVAR RunCodeStart "/*"
:SETVAR RunCodeEnd "*/"

$(RunCodeStart)
DROP DATABASE $(DatabaseName);
$(RunCodeEnd)

The only thing to realize is that you can’t embed GO in the comment marks like this. With the first method, you can comment out the GO, or add it back. GO is a batch separator, and it is part of the too, but while you can safely comment out code including GO using:

/*
GO
*/

You will get an error if you add GO to the code using start and ending comment marks that indicate you are missing comment blocks.

Summary

The code samples presented are all very close to the level of a hack, but when you need variables that cross batches, this is the only way. SQLCMD variables also are nice because they simply are expanded as text into your code, making them easier to use than traditional variables for a lot of admin tasks.

Using the methods presented is kind of tricky for sure, but for those semi-rare occasions where you need to skip some code in a T-SQL file, where traditional control of flow language in T-SQL won’t work, these techniques work quite nicely.

 

The post Optional Code in T-SQL Scripts using SQLCMD appeared first on Simple Talk.



from Simple Talk https://ift.tt/K5yMDgF
via

Friday, March 3, 2023

Retrieving MySQL data from within Python

Applications of all types commonly access MySQL to retrieve, add, update, or delete data. The applications might be written in Python, Java, C#, or another programming language. Most languages support multiple methods for working with a MySQL database and manipulating its data.

The approach you take when accessing MySQL will depend on the programming language you’re using and the connector you choose for interfacing with the database. Whatever approach you take, the same basic principles generally apply to each environment. You must establish a connection to the database and then issue the commands necessary to retrieve or modify the data.

Because MySQL can play such an important role in application development, I wanted to provide you with an overview how to access MySQL data from within your application code. This article demonstrates how to use the MySQL Connector from within Python to establish a connection and run a query. Although I focus on only one approach to accessing MySQL, the examples should give you a general idea of what it takes to connect to a database and retrieve the information you need.

When I created the examples in this article, I used a Mac computer that was set up with the following components:

  • MySQL 8.0
  • Python 3.10
  • PyCharm Community Edition IDE
  • MySQL Connector/Python 8.0 module

If you want to try out the Python code snippets for yourself, you’ll need to set up a comparable environment, including the MySQL Connector module. You can find information about installing the module in the MySQL documentation. On my system, I used pip to add the module. Pip is a package installer for Python that makes it very easy to deploy a module.

Note: If you want to follow along, the table definition and initial set of data is included as an appendix to this article.

Defining a connection to MySQL

When connecting to a MySQL database in Python, you need to take several basic steps:

  1. Import the connect method from the MySQL Connector module.
  2. Use the connect method to create a connection object that includes your connection details.
  3. Use the connection object to run your data-related code.
  4. Close the connection.

When you create your connection, Python will generate either a MySQLConnection object or CMySQLConnection object. The object generated depends on whether you have the Connector C extension installed on your system. The extension interfaces with the MySQL C client library, which can help improve performance for large result sets. Because the extension was installed on my system, Python generated a CMySQLConnection object when I ran the example code; otherwise, it would have generated a MySQLConnection object.

You can find more information about the C extension here, but you don’t really need to worry about it for the exercises in this article. I point it out only so you’ll understand why your IDE might indicate one object type over the other, if you happen to notice the difference. With that in mind, take a look at the following Python code snippet, which establishes a connection to the travel database:

# import the connect method
    from mysql.connector import connect

# define a connection object
conn = connect(
      user = 'root',
      password = 'SqlPW_py@310!ab',
      host = 'localhost',
      database = 'travel')

print('A connection object has been created.')

# close the database connection
conn.close()

Note: Be careful where you include your password, especially the root user password in your code. A discussion of security is far beyond the scope of this article. It’s up to you to take the steps necessary to secure your application from the wide range of potential threats that can put your data at risk.

The code starts by running a from statement that imports the connect method from the MySQL Connector module (mysql.connector). The code then uses the method to create a connection object, which is assigned to the conn variable. In this case, the connect method takes four arguments: user, password, host, and database, all of which should be self-explanatory. The four arguments are enclosed in parentheses and separated by commas.

The connect method supports many more arguments than what I’ve included here. You can find details about the arguments in this MySQL topic, along with other information about connecting to MySQL.

After creating the connection object, I run a print statement. I added this statement primarily as a placeholder to show you where you would normally insert your data-related code, which I’ll be discussing later in the article. For now, the print statement simply returns a sentence stating that a connection object has been created.

The final step is to close the connection. For this, you need only call the close method on the connection object. Otherwise, that’s all you need to do to establish a connection with a MySQL database. In most cases, you should find the process fairly straightforward.

For more details on connecting to MySQL via the connect method of the connector object, check here in the MySQL documentation.

Reading connection data from a file

In the previous example, the connect method included the arguments necessary to connect to the MySQL instance. However, the method can also pull the arguments from a MySQL option file, which is a text file that usually takes the .cnf extension. To demonstrate how this works, I created a file named connectors.cnf and added the following information to the file:

[client]
user = root
password = SqlPW_py@310!ab
host = localhost
database = travel

These are the same arguments you saw in the previous example, without the quotation marks or commas. The arguments are grouped together under the [client] option group. By default, the connect method reads from the [client] and [connector_python] groups in the referenced option file.

Once you have your option file in place, you can access it from within your Python code by specifying the option_files argument in your connect method, as shown in the following example:

# import the connect method
from mysql.connector import connect

# define a connection object
conn = connect(option_files =
  '/users/mac/documents/config/connectors.cnf')

# verify the connection information
print('The user ' + conn.user + ' is connected to the '
       + conn.database + ' database.')

# close the database connection
conn.close()

Instead of listing the individual arguments in the connect method, I’ve added the option_files argument, along with the path where I saved the connectors.cnf file. When I ran the Python code, it pulled the connection information from the file and used it when creating the connection object.

Note: My use of an option file is by no means meant to suggest that this approach is enough to secure your Python/MySQL connections. As stated previously, this code is to demo the capabilities that are possible.

For this example, I also modified the print statement. I did this to verify that I’m pulling the correct information from the option file. The statement returns the name of the user and database, which I assumed was enough to verify that everything was working properly. To retrieve this information, I used the conn variable to specify the user property and database property, which are defined on the connection object. I then concatenated these values with the string values necessary to make up the returned statement.

Catching errors in your MySQL connection

When accessing MySQL from your Python applications, you can include exception handling that’s specific to your MySQL connection. To add exception handling, enclose the connection code in a try block and then add an except statement to catch any MySQL errors, as shown in the following example:

# import the connect and Error methods
from mysql.connector import connect, Error

# try to run the block of code
try:

  # define a connection object
  conn = connect(option_files =
    '/users/mac3/documents/config/connectors.cnf')

  # verify the connection information
  print('The user ' + conn.user + ' is connected to the '
    + conn.database + ' database.')

  # close the database connection
  conn.close()

# catch exception and print error message
except Error as err:
  print('Error message: ' + err.msg)

Notice that the code now imports the Error method, along with the connect method. The code then includes a try block that contains the connection-related code and the print statement. This is the same code you saw in the previous example.

After the try block, the code includes an except statement that uses the Error method to catch the MySQL exception and create an error object, which is assigned to the err alias. This is followed by a print statement that returns the contents of the msg property that is defined on the error object.

When you run this code, Python will first try to execute the code in the try block. If there are no errors, the code runs until completion (when the connection is closed). If a MySQL error is encountered, code execution stops, and Python returns the error message. For example, if the database doesn’t exist, you’ll receive a message stating that the specified database is unknown.

Note that the error handling I’ve included here is specific to the MySQL Connector. If an error occurs for another reason, such as a problem in the Python syntax, the error will not be returned by the print statement. Python will treat the error as it would normally treat other types of errors. If you want to include error handling for the Python code itself, you must specifically add it to your application.

Querying data in a MySQL database

Up to this point, the examples in this article have been concerned only with connecting to a MySQL database, essentially verifying that such connections are possible. In the real world, however, you’ll want to do a lot more with your applications than simply check whether you can connect to a database. One of the most common scenarios is to retrieve data from the database, which you can do in a few basic steps:

  1. Use the connection object to invoke the cursor method and create a cursor object.
  2. Define your query and save it to a variable.
  3. Use the cursor object to invoke the execute method and run your query.
  4. Use the cursor object to invoke a method such as fetchall to capture the query results and save them to a variable.
  5. Use the variable with the results to carry out other data-specific operations.
  6. Close the cursor.

These steps are in addition to establishing the basic connection. In fact, you need the connection object to create your cursor, which makes it possible to run queries against the target database. The following Python code shows an example of how I used these steps to retrieve data from the airplanes table in the travel database:

# import the connect and Error methods
from mysql.connector import connect, Error

# try to run the block of code
try:

  # define a connection object
  conn = connect(option_files =
    '/users/mac3/documents/config/connectors.cnf')

  # open cursor, define and run query, fetch results
  cursor = conn.cursor()
  query = 'SELECT plane_id, plane, max_weight FROM airplanes'
  cursor.execute(query)
  result = cursor.fetchall()

  # print the results in each row
  for r in result:
    print(r)

  # close the cursor and database connection
  cursor.close()
  conn.close()

# catch exception and print error message
except Error as err:
  print('Error message: ' + err.msg)

After defining the connection, I used the conn variable to call the cursor method and create a cursor object, which I assigned to the cursor variable. I then defined a SELECT statement and assigned it to the query variable.

Next, I used the cursor object to call the execute method, passing in the query variable in as an argument. I then used the cursor object to call the fetchall method in order to retrieve all the rows returned by the SELECT statement. You can also use the fetchall method to fetch a certain number of rows if the results of the query are very large. Then you would fetch N rows, the output those rows, then fetch N more rows. Finally, I assigned the results to the result variable, which stores the rows of data as a series of tuples.

After you capture the result set in a variable, you can use the variable’s data in your application however you need to. For this example, I created a simple for loop that iterates through the result set and assigns data to the r variable one row at a time. The contents of the r variable are then printed out for each loop. Finally, I used the cursor object to call the close method in order to close the cursor. On my system, Python returned the following results after I ran the code:

(1001, 'A340-600', 837756)
(1002, 'A350-800 XWB', 546700)
(1003, 'A350-900', 617295)
(1004, 'A380-800', 1267658)
(1005, 'A380-843F', 1300000)
(1006, 'A.109 Airedale', 2750)
(1007, 'A.61 Terrier', 2400)
(1008, 'B.121 Pup', 1600)
(1009, 'B.206', 7500)
(1010, 'D.5-108 Husky', 2400)
(1011, 'Baron 56 TC Turbo Baron', 5990)
(1012, 'Baron 58 (and current G58)', 5500)
(1013, 'Beechjet 400 (same as MU-300-10 Diamond II)', 15780)
(1014, 'Bonanza 33 (F33A)', 3500)
(1015, 'Bonanza 35 (G35)', 3125)
(1016, '747-8F', 987000)
(1017, '747-SP', 696000)
(1018, '757-300', 270000)
(1019, '767-200', 315000)
(1020, '767-200ER', 395000)

Once you understand the logic of how to retrieve data, the process itself is fairly straightforward. In many cases, however, your SELECT statement will be much longer than the one in this example. If you want to spread your statement over multiple lines, you can enclose each line in quotes and then enclose all lines in parentheses, as shown in the following example:

# import the connect and Error methods
from mysql.connector import connect, Error

# try to run the block of code
try:

  # define a connection object
  conn = connect(option_files =
    '/users/mac3/documents/config/connectors.cnf')

  # open cursor, define and run query, fetch results
  cursor = conn.cursor()
  query = ('SELECT plane_id, plane, max_weight FROM airplanes ' 
    'WHERE max_weight > 100000 ' 
    'ORDER BY max_weight DESC')
  cursor.execute(query)
  result = cursor.fetchall()

  # print the results in each row
  for r in result:
    print(r)

  # close the cursor and database connection
  cursor.close()
  conn.close()

# catch exception and print error message
except Error as err:
  print('Error message: ' + err.msg)

When your query spans multiple lines in this way, be sure to include the necessary space at the end of each line (except the last) so your statement is submitted to MySQL correctly. For this example, the Python code returns the following results:

(1005, ‘A380-843F’, 1300000)
(1004, ‘A380-800’, 1267658)
(1016, ‘747-8F’, 987000)
(1001, ‘A340-600’, 837756)
(1017, ‘747-SP’, 696000)
(1003, ‘A350-900’, 617295)
(1002, ‘A350-800 XWB’, 546700)
(1020, ‘767-200ER’, 395000)
(1019, ‘767-200’, 315000)
(1018, ‘757-300’, 270000)

As you can see, the results include only airplanes with a max_weight value greater than 10000. The results are also sorted in descending order based on the max_weight values.

Passing variable values into your query

When using the MySQL Connector to query data, it can often be useful to pass variable values into your SELECT statement (or whichever SQL statement you’re defining). You can do this by including special %s markers as placeholders where the variable values should be inserted. The following example shows a SELECT statement that contains two of these markers:

# import the connect and Error methods
from mysql.connector import connect, Error

# try to run the block of code
try:

  # define a connection object
  conn = connect(option_files =
    '/users/mac3/documents/config/connectors.cnf')

  # open cursor and define query
  cursor = conn.cursor()
  query = ('SELECT plane_id, plane, max_weight FROM airplanes '
    'WHERE max_weight BETWEEN %s AND %s '
    'ORDER BY max_weight DESC')

  # define input variables
  weight_start = 1000
  weight_end = 10000

  # pass variables into query and fetch results
  cursor.execute(query, (weight_start, weight_end))
  result = cursor.fetchall()

  # print the results in each row
  for r in result:
    print(r)

  # close the cursor and database connection
  cursor.close()
  conn.close()

# catch exception and print error message
except Error as err:
  print('Error message: ' + err.msg)

I added the %s markers to the WHERE clause as part of a BETWEEN operator. The variable values will be inserted in place of the markers when the SELECT statement is executed.

For this example, I hard-coded the variable values and assigned them to the weight_start and weight_end variables. In most cases, you’ll likely want to capture these values through user interaction or other means and then assign them dynamically to the variables at runtime, but for now, hard-coding them is enough to demonstrate how this process works.

After you define your variables, you can pass them in as an argument to the execute method that runs your query. The variables should be added as a second argument, enclosed in parenthesis and separated with a comma. In addition, they must be specified in the same order that you want them applied to the query. The Python code should now return the following results:

(1009, 'B.206', 7500)
(1011, 'Baron 56 TC Turbo Baron', 5990)
(1012, 'Baron 58 (and current G58)', 5500)
(1014, 'Bonanza 33 (F33A)', 3500)
(1015, 'Bonanza 35 (G35)', 3125)
(1006, 'A.109 Airedale', 2750)
(1007, 'A.61 Terrier', 2400)
(1010, 'D.5-108 Husky', 2400)
(1008, 'B.121 Pup', 1600)

As expected, the results include only those airplanes with a max_weight value between 1000 and 10000. If you had built your application to capture user input, the user might have specified different variable values, which would have been passed into the application dynamically.

Getting started with Python and MySQL

In this article, I’ve introduced you to how to use the MySQL Connector in Python to access a MySQL database and retrieve data from one of its tables. As with most aspects of application development, the approach I’ve taken here is only one of a variety of methods you can use to achieve the same results. You could have constructed your code differently, used a different connector, or even used a different programming language. Even so, what I’ve shown you should still give you a general idea of how to retrieve MySQL data within your application.

Be aware, however, that this article is by no means meant to be a comprehensive tutorial on how to use Python to develop a data-driven application. Although Python might be considered a lightweight language when compared to a one such as Java or C#, it is still a comprehensive language with many of its own complexities and nuances. Before you build an application that connects to MySQL, you should have a solid foundation in the language and what it takes to create an efficient and secure application. This article is meant only as a starting point for accessing MySQL data, although it should be enough to show you how easily you can interface with a MySQL database and retrieve the necessary data.

Appendix: Preparing your MySQL environment

The Python examples in this article connect to the travel database on a local MySQL instance and retrieve data from the airplanes table, which includes a foreign key that references the manufacturers table. This is the same database and tables you saw in previous articles in this series, although I’ve limited the data that I inserted into the tables to only a small amount, which is all that’s needed to demonstrate the concepts in this article. If you plan to try out the examples, start by running the following script against your MySQL instance:

DROP DATABASE IF EXISTS travel;

CREATE DATABASE travel;

USE travel;

CREATE TABLE manufacturers (
  manufacturer_id INT UNSIGNED NOT NULL,
  manufacturer VARCHAR(50) NOT NULL,
  create_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  last_update TIMESTAMP NOT NULL 
    DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (manufacturer_id) );

CREATE TABLE airplanes (
  plane_id INT UNSIGNED NOT NULL,
  plane VARCHAR(50) NOT NULL,
  manufacturer_id INT UNSIGNED NOT NULL,
  engine_type VARCHAR(50) NOT NULL,
  engine_count TINYINT NOT NULL,
  max_weight MEDIUMINT UNSIGNED NOT NULL,
  wingspan DECIMAL(5,2) NOT NULL,
  plane_length DECIMAL(5,2) NOT NULL,
  parking_area INT GENERATED ALWAYS AS ((wingspan * plane_length)) STORED,
  icao_code CHAR(4) NOT NULL,
  create_date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  last_update TIMESTAMP NOT NULL 
    DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (plane_id),
  CONSTRAINT fk_manufacturer_id FOREIGN KEY (manufacturer_id) 
    REFERENCES manufacturers (manufacturer_id) );

The script will create the travel database and add the manufacturers and airplanes tables in the proper order to accommodate the foreign key defined in the airplanes table. After you the create the tables, you can then run the following INSERT statements:

INSERT INTO manufacturers (manufacturer_id, manufacturer)
VALUES (101,'Airbus'), (102,'Beagle Aircraft Limited'), 
  (103,'Beechcraft'), (104,'Boeing');

INSERT INTO airplanes 
  (plane_id, plane, manufacturer_id, engine_type, engine_count, 
    wingspan, plane_length, max_weight, icao_code)
VALUES
  (1001,'A340-600',101,'Jet',4,208.17,247.24,837756,'A346'),
  (1002,'A350-800 XWB',101,'Jet',2,212.42,198.58,546700,'A358'),
  (1003,'A350-900',101,'Jet',2,212.42,219.16,617295,'A359'),
  (1004,'A380-800',101,'Jet',4,261.65,238.62,1267658,'A388'),
  (1005,'A380-843F',101,'Jet',4,261.65,238.62,1300000,'A38F'),
  (1006,'A.109 Airedale',102,'Piston',1,36.33,26.33,2750,'AIRD'),
  (1007,'A.61 Terrier',102,'Piston',1,36,23.25,2400,'AUS6'),
  (1008,'B.121 Pup',102,'Piston',1,31,23.17,1600,'PUP'),
  (1009,'B.206',102,'Piston',2,55,33.67,7500,'BASS'),
  (1010,'D.5-108 Husky',102,'Piston',1,36,23.17,2400,'D5'),
  (1011,'Baron 56 TC Turbo Baron',103,'Piston',2,37.83,28,5990,'BE56'),
  (1012,'Baron 58 (and current G58)',103,'Piston',2,37.83,29.83,5500,'BE58'),
  (1013,'Beechjet 400 (same as MU-300-10 Diamond II)',103,'Jet',2,43.5,48.42,15780,'BE40'),
  (1014,'Bonanza 33 (F33A)',103,'Piston',1,33.5,26.67,3500,'BE33'),
  (1015,'Bonanza 35 (G35)',103,'Piston',1,32.83,25.17,3125,'BE35'),
  (1016,'747-8F',104,'Jet',4,224.42,250.17,987000,'B748'),
  (1017,'747-SP',104,'Jet',4,195.67,184.75,696000,'B74S'),
  (1018,'757-300',104,'Jet',2,124.83,178.58,270000,'B753'),
  (1019,'767-200',104,'Jet',2,156.08,159.17,315000,'B762'),
  (1020,'767-200ER',104,'Jet',2,156.08,159.17,395000,'B762');

The INSERT statements first populate the manufacturers table and then the airplanes table. Be sure to run the statements in the order shown here because of the foreign key.

 

The post Retrieving MySQL data from within Python appeared first on Simple Talk.



from Simple Talk https://ift.tt/QvBLGOw
via

Wednesday, March 1, 2023

Getting Out of Character

Pre-Unicode

Younger programmers have grown up with ASCII and Unicode as the only ways of representing character data in a computer. But in the dark ages, before we invented dirt and entered into the stone age, there were other contenders.

The Control Data Corporation used a 6-bit binary scheme called Field Data. This was due to their hardware. Thanks to IBM’s dominance in the market at the time, punch cards were encoded with Hollerith and later their mainframes and mid-range computers used Extended Binary Coded Decimal Interchange Code (EBCDIC), an 8-bit scheme based off Hollerith. Unfortunately, there were three different versions of EBCDIC from IBM as well as some national code variations.

Back in the days of telegraphs, teletypes used Baudot (invented in the 1870’s) for their five channel paper tapes. (The inventor’s name is also where we get the term “baud” for transmission rates.) The coding scheme was improved a bit to become Murray code by 1901. One of the improvements was that the codes now included formatting codes, such as Carriage Return, Line Feed, Delete and so forth, which survived into the encoding schemes which came afterwards.

The debut of 7-bit ASCII in 1963 is where many programmers began learning programming. Mini-computers first used eight channel teletypes as their input device. Teletypes were relatively cheap and highly available back then.

Today, since computers have gotten smaller and less dominated by IBM, we use American Standard Code for Information Interchange (ASCII), which is a 7-bit character code. Each character is usually stored in one byte and the extra bit becomes a check digit or a way to shift to more ISO/IEC 8859 characters.

ISO/IEC 8859 was a joint ISO and IEC series of standards for 8-bit character encodings. The ISO working group for this standard has been disbanded. It’s job is now handled by Unicode. It was used for the accented letters in European languages that were based on the Latin alphabet. But coverage is not complete. For example, for compatibility, Dutch has been using “ij” as two letters in modern usage instead of one symbol. Likewise, in 2010, the Spanish Academy gave up “ch” and “ll” as separate letters for alphabetical order. (The term for these characters that tie two base characters together as one is a ligature. )

SQL added datatypes NATIONAL CHARACTER and NATIONAL VARYING CHARACTER. Nobody ever uses their full names, so we have NCHAR(n) and NVARCHAR(n) in our declarations. When we originally made this part of the language, there was no Unicode created yet, so they depended on whatever your implementation defined them as. It was assumed that this would depend on a national standards organization already having representations for the special characters they need for their language. We did not imagine it becoming as generalized as Unicode.

Unicode

The idea for Unicode began in 1988 and was formalized in 1991 in California. It was going to be a new character encoding under the name “Unicode”, sponsored by engineers at Xerox and Apple. The Unicode Consortium has more details on their website and today (2023 February) they are up to release 15.0.0 (and there is a 15.1.0 in draft mode).

Initially, academic, or political groups that had interest in obscure alphabets or writing systems made contributions to the character sets. Unicode 15.0.0 added 4489 characters, for a total of 149, 186 characters. These additions include 5 new scripts, for a total of 159 scripts, as well as 37 new emoji characters.

Today the big fights are about emoji symbols, and I have no idea why some of these characters are vital to data processing, but they are there!

Types of Characters

Characters can be broadly grouped into major categories: Letter, Mark, Number, Punctuation, Symbol, Separator and Other. The names pretty well explain themselves but do have more detailed definitions within each category. For example, letters are ordered by uppercase, lowercase, ligatures (such as æ and œ in English and French) containing uppercase, ligatures containing lowercase, and finally the lowest sort order, an ideograph (like a symbol in Chinese, for example) or a letter in a unicase alphabet. (Unicase alphabets only have one case instead of an upper and lowercase.)

This settles the question about how to handle upper and lowercase letters. It used to be that some correlations would put the lowercase version of a letter immediately after the uppercase version when setting up alphabetical order.

As a trivia question, can you name the alphabets which you do have a case system? We have Latin, Greek, Cyrillic and Arabic; the last one always surprises people, but letters have an initial form, a middle form (remember, it is a connected script), a terminal form and finally a standalone form.

Punctuation includes the underscore and dashes. The fun part comes with all the ways to make brackets. Brackets are considered part of punctuation, not math symbols.

Numbers include vulgar fractions (one number placed above another and a fraction bar, also known as a slash, like ½) and Roman numerals but do not include algebraic symbols. We also have problems with quote marks; do you do a separate open and close quote mark? Which pair do you use? Some Slavic languages prefer >> << and others use << >>.

This is just the beginning and it gets more complicated. For actual text, we still have a lot of legacy encoding systems in the typography business. Early adopters tended to use UCS-2 (the fixed-width two-byte precursor to UTF-16) and later moved to UTF-16 (the variable-width current standard), as this was the least disruptive way. The most widely used such system is Windows NT (and its descendants, 2000, XP, Vista, 7, 8, 10, and 11). Windows uses UTF-16 as the sole internal character encoding. The Java and .NET bytecode environments, macOS, and KDE also use it for internal representation. Partial support for Unicode can be installed on Windows 9x through the Microsoft Layer for Unicode.

For database people, the most important characteristic of Unicode is that all languages will support the simple Latin alphabet, digits, and a limited set of punctuation. The reason this is important is that ISO abbreviations for most units of measure and other standards use only these characters. This lets you insert them into the middle of the weirdest, most convoluted looking alphabets and symbol systems currently on earth, as well as mixing them in with emojis.

This also is a key concept if you ever must design an encoding system, don’t get fancy. Keep your encoding schemes in simple Latin letters and digits and use the “fancy stuff” for text.

Unicode Normalization

If you are old, you might remember a thing called a typewriter. It uses physical type to make images on paper by physically striking an inked ribbon. When we wanted a special character, we had to physically type the characters by either adding extra type elements to the machine (look at the IBM Selectric typewriter “golf balls” with special characters or before that, the Hammond multiplex) or use the backspace on these machines to create a single symbol.

Unicode came up with something like this. Despite the incredibly large range of symbols available to you, you can combine various diacritical marks and letters on top of each other. Without going into much detail, the Unicode standard gives four kinds of normalization. This means that I can put together string of Unicode characters, run them through an algorithm, and if they are equivalent, then I can reduce them to one single display character, or, at worst reduce them into a unique string of characters.

As an example, Å can be written in three ways in Unicode. The first to actually use the Å symbol as a letter of the Swedish alphabet (is your data Swedish?), use the symbol as the unit of measure (the angstrom is a unit of length that equals 0.1 nanometer), or build it from the pieces (uppercase A with a superior small circle accent, using zero spacing between two Unicode characters).

All three look the same when printed, but the first two have completely different meanings and the third is ambiguous, since it might be an attempt to go either of the first two ways.

Comparisons

The Unicode Standard defines two formal types of equivalence between characters when doing comparisons:

  • Canonical means that equality characters or sequences of characters represent the same abstract character, and which when correctly displayed should always have the same visual appearance and behavior.
  • Compatibility means that characters are not the same, but still mean the same thing.

For canonical equivalence, let’s consider Vietnamese on a menu at a restaurant (no, I do not read or speak Vietnamese). Their script was constructed for them by French missionaries, which is why it has a Latin alphabet as its basis. An individual letter can have several diacritical marks on it (marks above other characters that change the sound, such as the accent mark in fiancé), and the order that those marks are placed on the base letter don’t really matter; at the end of the construction, we get a single character regardless of the order in which it was constructed. You might have noticed, a pen has a much larger character set than your computer.

Korean, or Hangul as it is more properly called, is actually arranged from phonetic pieces in two dimensions to build syllables that are seen as single characters. The placement and the shape of the phonetic parts follow strict rules of organization. For example, in Hangul 가 is actually built from ᄀ +ᅡ. The leftmost unit changes shape. These two versions of 가 are considered canonically equivalent.

You can also pull a character apart. At one point, the use of ligatures was common in typesetting. For example, the “fi” ligature changes into its components “f” and “i”, and likewise for “ffl” , “ffi”, “st” and “ct” ligatures that were used mostly in the 1800s.

Compatibility equality is less strict and deals with characters that are close. For example, these two characters are not formally equal, but they are compatible with each other:

A picture containing text, furniture, seat, table Description automatically generated

But wait! It gets even worse with mathematical notation. Just consider fractions; Is “1/4” the same thing as “¼”? The standard considers them compatible, but how many different ways are there to write logical operators? Comparison operators? Various mathematical societies have different typesetting standards, and it can get as bad as any written language.

For more details on this topic, check out this page on the Unicode.org website.

Normalization

Unicode Normalization Forms are formally defined normalizations of Unicode strings which make it possible to determine whether any two Unicode strings are semantically equivalent to each other. The goal of the Unicode Normalization Algorithm for database people Is to guarantee that Comparison operators and join operators, as well as SQL clauses like ORDER BY and GROUP BY will work without surprising users.

ANSI/ISO Standard SQL

Officially once you get into SQL, you can use statements to modify the collation character sets involved. I seriously doubt that many of you will ever use this in your career, as you are probably better off using whatever default you get with your SQL product. However, the more you understand what went into determining how collations are created the better. So, for the record, here are the statements from the CREATE COLLATION statement that some RDBMS’s provide (others, like SQL Server simply provide you thousands of choices.)

Where do accented letters fit in the collation? Some languages, put their accented letters at the end of the alphabet, and some put each letter after its unaccented form. When German was doing its spelling reforms, this was a big debate about whether the Umlaut-ed three letters made them separate letter the end of the alphabet or they were just different forms the base letter.

Esperanto puts its accented letters immediately after the unaccented form; ”a, b, c, ĉ, d…”; However, since the circumflex was not always available, Esperanto also has the convention of using the combination of a base letter followed by x; “a, b, c, cx, d..” Since the X is not used in the Esperanto alphabet.

Officially, in some SQL implementations you can change all of this at the database level and override the Unicode conventions. If you want to further mess up local language settings, you can also use a

CREATE CHARACTER SET < name of character set> AS 
    < character set source> [<collation clause>] 
    <character set source> ::= GET < character set specification>.

Likewise, there is a CREATE COLLATION statement in the standard.

CREATE COLLATION <correlation name>
FOR <Character set specification>
< from existing correlation name> [< pad characteristic>]
 < pad characteristic> ::= NO PAD | PAD SPACE

The pad characteristic that has to do with how strings are compared to each other. This is based on SQL versus the xBase language conventions. NO PAD follows the xBase convention of truncating the longer string before doing the comparison. The PAD SPACE option pads the shorter string with spaces and then begins comparing the strings character by character from left to right. This is the default in SQL.

Normalization

Unicode Normalization Forms are formally defined normalizations of Unicode strings which make it possible to determine whether any two Unicode strings are equivalent to each other. Depending on the particular Unicode Normalization Form, that equivalence The goal of the Unicode Normalization Algorithm For database people Is to guarantee that SQL clauses ORDER BY and GROUP BY will actually work without surprising us.

The two most common emoticon combinations were probably “:-)” and “:-(“. These conventions existed in the West and assumed that the reader would turn the line 90° to read it. Japanese users at the time, laid things out horizontally. Emojis evolved from these text based character expressions, but are actually cartoon figures.

There currently are over 800 different emojis and these are sent over 6 billion times a day through Facebook. According to Google, over 90 percent of the world’s population uses emojis and the most popular emoji employed on both Facebook and Twitter is the ‘laugh cry’ face. This makes me fear the literacy level among computer people.

General Advice on Handling Languages in Data Bases

There is a safety rule in life that says: “do not get tattoos in a languages in which you are not fluent.” This rule also applies to databases and text documents. Many years ago, a Canadian Sunday newspaper ran an article on Chinese tattoos that non-Chinese speakers got. What they actually said were things like “this cheap bastard does not tip tattoo artist” And worse. Perhaps you should find someone who does speak the language fluently and asked him to check what’s going into your database. Even if it isn’t obscene or absurd, it still may not be what you meant to put into the database.

Try to keep things as simple as possible and use a minimal character set. You will want to move your data from one platform to another. The days of a one vendor shop have been over for decades.

Remember that SQL is based on a tiered architecture. That means you don’t know when a new kind of presentation layer is going to be added to your database. In a serious application, the worst thing you can do is write SQL that is totally dependent on one release of one product from one vendor. Clean, simple, and portable are good.

 

The post Getting Out of Character appeared first on Simple Talk.



from Simple Talk https://ift.tt/1RdIZkJ
via