Quantcast
Channel: Symantec Connect - Articles
Viewing all articles
Browse latest Browse all 1863

15 tips to optimize SQL queries!!!!

$
0
0

hello happy tuesday in this article I will talk about how we can optimize our searches under the optimization of SQL.

ok many have already said it for articles through this beautiful page but it is always good to refresh our memories so we have to start knowing that it is SQL

Currently the development of computer and computational technology produces a large volume of data on a daily basis. These data need to be sorted and stored for later use or analysis, for this large data warehouses called databases were created.

If your company or application points to a bright future, with great potential for growth, this must have a database, which must adjust to the particular needs of each type of company or application.

But, what is a database?

A database is a separate application that stores a collection of data. So we can say that it is a collection of information organized by fields, records and files, so that you can quickly select the pieces of data that are needed.

Relational database

A database is relational when it complies with the relational model, which refers to the relationship that exists between the different entities or tables in the database. Also known as relational database management systems (RDBMS), which allow us to store and manage large amounts of data. The data is stored in different tables and the relationships are established using primary keys or other keys known as external or foreign keys.

There are a number of relational database management systems and each of them has a different way to manage their data, some examples of RDBMS are: Oracle, MySQL, SQL Server, among others.

However, over the years, these were unified and universalized to make way for better techniques and better ways of handling. That's how SQL was born.

SQL (Structured Query Language) is a standard and interactive language of access to relational databases that allows to specify diverse types of operations in them, thanks to the use of algebra and relational calculations, SQL offers the possibility of consulting with the objective of retrieving information from databases in a simple way. The queries take the form of a command language that allows you to select, insert, update, find out the location of the data, and more.

WHY LEARN SQL?

SQL is an international standard declarative communication language within the databases that allows us all to access and manipulate data in a database, and it can also be integrated into programming languages, for example ASP or PHP, and in combination with any specific database, for example MySQL, SQL Server, MS Access, among others.Database management is a skill that is increasingly demanded and rewarded in the business world today. The average salary for SQL programmers in some countries like E.E. U.U., according to (Indeed.com), is $ 92,000 per year, for SQL DBA (database administrators) can reach an average salary of $ 97,000 per year.

the skills in SQL to work in programs and databases have become more necessary, valuable and rewarded. Companies are looking for the help of people who know SQL. They know the value that someone expert in SQL brings to their company and seek to employ these people.

Since the 70s, SQL has been used in any relational database around the world, its structure and characteristics have remained stable since then.

n the database, with adding a few simple changes you will achieve great advances. SQL gives you the power to answer any question you ask about your data, either What were last year's sales? What is the average customer satisfaction index? At what rate have we reduced expenses since last summer? SQL transforms these questions in the form of queries and will bring the data and display the response in the form of information.

since we remember that it is a database and we understand why we must learn SQL. Well, you can get a hundred percent of this fabulous article ... here we go 

15 tips to optimize SQL queries

1.- Choose the most appropriate storage engine

The main search engines are MyISAM and InnoDB, but there are many others like Aria, TokuDB, XtraDB or archive.

MyISAM is more appropriate in those cases where SELECT queries predominate.

Its main features are:
- Lock at table level
- Greater speed in SELECT queries
- High compression
- Full-text searches
- Does not support foreign keys

InnoDB is more appropriate if the INSERT, UPDATE or DELETE predominates

Its main features are:
- Block level blocking
- Allows foreign keys
- Full-text searches as of version 5.6.4
- Allow transactions

Special mention for Aria (as an alternative to MyISAM) and Archive (for storing logs).

2.- Avoid select *

Select only those columns that you are really going to use.

Selecting more columns than necessary increases the time it takes to execute the query and the transfer time if the DB is on a separate server.

All right:
SELECT id, title FROM tasks;

Wrong:
SELECT * FROM tasks;

3.- Limit the number of results

Utiliza una clausula LIMIT si solo necesitas una determinada cantidad de resultados o si estás filtrando por id y por lo tanto solo hay un resultado como máximo.

Bien:
SELECT id, titulo FROM tareas where id = 555 LIMIT 1;

Mal:
SELECT id, titulo FROM tareas where id = 555;

4.- Avoid subqueries

For each subquery you add, MySQL will perform an additional query for each record of the main query.

If you have a query that shows 100 results, you will make 100 additional queries for each subquery.

All right:
SELECT t.id, t.name, salary
FROM workers t
JOIN wages s ON s.worker = t.id

Wrong:
SELECT t.id, t.name, (SELECT salary from salaries s where s.worker = t.id) as 'salary'
FROM workers t

5.- Save IP addresses as unsigned int

Save the IP addresses as an unsigned integer. PHP allows you to convert an IP with ip2long and long2ip to revert the process.

6.- Optimize the query for the cache

Algunas funciones impiden a MySQL cachear la consulta, por ejemplo, la función now() obtiene la fecha/hora actual cada vez que se ejecuta.

Una solución sería obtener la fecha en el lenguaje que estés usando junto con SQL (PHP, JAVA, etc)

7.- Join with the same type of column

Making a join with a column of the same type and size is faster.

8.- Autoincrementales unsigned

The autoincrementals can not be negative, setting the column as unsigned gain an extra bit, which allows to save larger values.

  

9.- EXISTS instead of IN

Use exists whenever possible, since EXISTS stops searching when it finds a match.

10.- Avoid using WILCARD (%)

The wilcard (%) seriously penalizes the performance, use it only if it is strictly necessary.

Wrong:
SELECT id, user, password
FROM users
WHERE user LIKE '% bruno%';

All right:
SELECT id, user, password
FROM users
WHERE user = 'bruno';

11.- Use CHAR instead of VARCHAR

CHAR is up to 50% faster than VARCHAR, although it has two disadvantages:
- It takes more space on disk
- It has a limit of 255 characters.

12.- Use the ENUM column type

Enum is a type of column that allows you to store a list of values ​​that are stored internally as a TinyInt.

It is ideal for storing fixed values, such as: colors, sex, states, etc.

13.- Avoid using ORDER BY RAND

When you add the ORDER BY RAND clause, what MySQL will do is:
- Select ALL the records that match your WHUE clause
- Load in memory or in a temporary table
- Associate random values ​​to each row
- Order them
- Shows N results according to the LIMIT clause

Some BBDD engines, such as Oracle, do not even allow this action.

14.- Save the logs in the ARCHIVE engine

Archive is designed to store a large volume of data.

It allows INSERT and SELECT, but not DELETE, REPLACE or UPDATE, although you can do a TRUNCATE to empty the table.

This engine is a good candidate to store logs

15.- The small columns are faster

Always use the right size for the column.

For example, if you are going to store a DNI, it does not make sense to have a field of 20 characters, since the DNI is made up of 9 characters.

I hope that this article will be as effective as I do since there are times when SQL becomes a headache. always limiting that when we play with codes and servers we owe a high quality protexxion. symantic endpoint has always been my companion in these games. and as not you will also help them. your beloved friend from the krossfox neighborhood says goodbye

 

 

 


Viewing all articles
Browse latest Browse all 1863

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>