As a developer I often come across SQL statements that are hardwired into the source code regardless of the programming language they are used in. It makes the code messy and unreadable when sometimes seeing large SQL statements chopped and concatenated in several string constants.
The information here may be trivial but I would like to share it anyway

PostgreSQL provides us the wonderful feature of stored procedures and user defined functions. These can abstract and hide the SQL plumbing back into the database leaving your source code much cleaner and readable.
Here is a simple example:
It is always a good practice to avoid code like this.
// You wonder what the heck this SQL does?
$sql = "select e.*";
$sql .= "from employee e inner join employee_department ed on e.empid = ed.empid ";
$sql .= "inner join department d on d.depid = ed.depid where d.manager=$1";
$result = $database->executeQuery($sql,$department);
Instead one could do the same like:
First create a stored procedure called
get_employee_list_by_department like:
create or replace function get_employee_list_by_department(integer) returns
setof employee as
$$
select
e.*
from
employee e inner join employee_department ed
on e.empid = ed.empid
inner join department d
on d.depid = ed.depid
where
d.manager = $1;
$$ language SQL;
Then call the stored procedure from your code like:
$result = $database->executeQuery("get_employee_list_by_department",$department);This is much cleaner and better don't you think? Also when your data structure changes you only have to change what is in the stored procedure not searching your code anymore.