How to Write SQL to Display Data From MySQL Databases

SQL is short for Structured Query Language, which is broadly used in a database system for data programming, such as structure designing and data manipulation. While it may seem easy at first glance, it takes time and practice to be perfect at this data language. Queries can be as simple as a single keyword or as sophisticated as a sentence with 20 keywords or even a whole structured routine.

MySQL is the most popular relational database system in the world, as the name suggests, it’s SQL compatible. It will be our subject in this series of articles in teaching you how to use the basic SQL commands to operate on databases and data tables.

How to display data from MySQL database?

The simplest SQL query to display data from a MySQL table should be:

SELECT * FROM table1;

Which selects all records by fields * from table table1. SELECT is the SQL command to display data or output something. The asterisk simply means all fields. There can be a conditional clause that indicates the conditions that must be met to display the data:

SELECT * FROM table1 WHERE id

Which selects and outputs all fields of all records from table1 that has an id field with value smaller than 100. You can spice things up by:

SELECT field1, field2, FROM table1 WHERE id = 50;

Which selects field1 and field2 only of all the records in table1 that has an id smaller than 100 AND larger than or equals to 50.

Therefore, AND means both conditions should be met to have a positive return. Other than AND, you have other logic operators such as OR and XOR. By OR you mean either this or that would do. By XOR, however, it means only one of them should be true and no more.

You can also have multiply stacked SELECT queries such as:

SELECT * FROM (SELECT * FROM table1);

Which is essentially the same with just the clause. This is useful when you need to combine or filter the selected results on multiple steps from more than one tables.

SELECT has a lot more uses, it can be used for numeric calculations:

SELECT 123 + 567;

Or date:

SELECT GETDATE();

Or count the total number of records in a table:

SELECT COUNT(*) FROM table1;

Otherwise, you may want to order the results by a specific field:

SELECT * FROM table1 ORDER BY id;

Which would output the results ordered by the id field in ascendant order. To order the results in descendant order:

SELECT * FROM table1 ORDER BY id DESC;



Source link