David's Blog

Web development and programming

How to execute a SQL Query from a Shell Script

MySQL Database

For this example we’re going to use MySQL as database management system. We’re going to operate over testdb database which contains the people table:

people table

And the following tuples:

+----+---------+-----+------------+
| id | name    | age | bornPlace  |
+----+---------+-----+------------+
|  1 | John    |  34 | London, UK |
|  2 | Patrick |  28 | NY, USA    |
+----+---------+-----+------------+

This is the MySQL SQL script for generating the testdb database:

create database testdb;
use testdb;
create table people(id INT, name varchar(100),
                    age INT, bornPlace varchar(100));
insert into people values(1,"John",   34,"London, UK");
insert into people values(2,"Patrick",28,"NY, USA");

 

Understanding execution of SQL Query from Shell

MySQL allows user to execute queries from the shell with MySQL command. The query can be passed as input using a pipe, like in this example: Continue reading