patternsqlMinor
Selecting Timesheets
Viewed 0 times
timesheetsselectingstackoverflow
Problem
I'm trying to improve my SQL syntax, take the following for the example
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?
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:
Note, the style changes:
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
SELECT *
FROM `Users:Timesheets`
WHERE
`start` >= '{$monday}'
AND (`finish` IS NULL OR `finish` <= '{$sunday}')
AND `username` = '{$username}'
AND `shift_type` = 'ONCALL'
ORDER BY `id` ASCNote, 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` ASCContext
StackExchange Code Review Q#72021, answer score: 3
Revisions (0)
No revisions yet.