HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Selecting Timesheets

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
timesheetsselectingstackoverflow

Problem

I'm trying to improve my SQL syntax, take the following for the example

SELECT * FROM `Users:Timesheets` 
WHERE 
`start` >= '{$monday}' 
AND `finish` = '{$monday}' 
AND `finish` IS NULL 
AND `username` = '{$username}' 
AND `shift_type` = 'ONCALL'

ORDER BY `id` ASC"


There must be a shorter way to achieve this or am I expecting too much?

Any insight to what I may be missing out on?

Solution

There's two style comments, and one logic comment. The logic comment is the most significant.... you can rewrite your query as:

SELECT *
FROM `Users:Timesheets` 
WHERE 
      `start` >= '{$monday}' 
  AND (`finish` IS NULL OR `finish` <= '{$sunday}')
  AND `username` = '{$username}' 
  AND `shift_type` = 'ONCALL'
ORDER BY `id` ASC


Note, the style changes:

  • always put each SQL clause on it's own line (the FROM on a new line).



  • Try to indent each clause in the where clause so that the precedence of the logic is represented by the indentation.



Update: I assume, based on the variable syntax, and so on, that this SQL is not a direct query, but is rather the input to some string substitution that expands the {$...} variables. This is potentially vulnerable to SQL Injection attacks. Are you sure you shoud be running your SQL this way? Have you considered prepared statements? Is this a prepared statement?

Code Snippets

SELECT *
FROM `Users:Timesheets` 
WHERE 
      `start` >= '{$monday}' 
  AND (`finish` IS NULL OR `finish` <= '{$sunday}')
  AND `username` = '{$username}' 
  AND `shift_type` = 'ONCALL'
ORDER BY `id` ASC

Context

StackExchange Code Review Q#72021, answer score: 3

Revisions (0)

No revisions yet.