Limit in sql syntax error

So here is the whole thing: SELECT * FROM sometable LIMIT 5*DATEDIFF(NOW(), '2011-08-30'), 5 Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL ser...

So here is the whole thing:

SELECT * FROM sometable LIMIT 5*DATEDIFF(NOW(), '2011-08-30'), 5

Error:

You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ‘*DATEDIFF(NOW(), ‘2011-08-30′), 5’ at line 1

The problem is clearly that LIMIT does not accept anything but integer apparently. It won’t accept 1+1 or (1+1) as value either. Is there a way around it?

And just so you don’t have to go and try, 5*DATEDIFF(NOW(), '2011-08-30') works just fine.

I am trying to fix this answer..

Community's user avatar

asked Aug 31, 2011 at 19:31

Bojan Kogoj's user avatar

3

NO, is not doable in plain mysql
(however, is possible via stored procedure, user defined function)

your case, it can easily replaced via a PHP call

$offset = 5*
        date_diff(new DateTime('now'), new DateTime('2011-08-31'))->format('%a');
$sql = "SELECT * FROM sometable LIMIT {$offset},5";

answered Aug 31, 2011 at 19:39

ajreal's user avatar

ajrealajreal

46.4k10 gold badges86 silver badges119 bronze badges

0

The limit must be an integer or local variable. From the MySQL docs:

The LIMIT clause can be used to constrain the number of rows returned
by the SELECT statement. LIMIT takes one or two numeric arguments,
which must both be nonnegative integer constants, with these
exceptions:

  • Within prepared statements, LIMIT parameters can be specified using
    ? placeholder markers.

  • Within stored programs, LIMIT parameters can be specified using integer-valued routine parameters or local variables as of MySQL
    5.5.6.

answered Aug 31, 2011 at 19:45

Kevin's user avatar

KevinKevin

52.9k15 gold badges98 silver badges129 bronze badges

0

when I am using this command to update table in PostgreSQL 13:

UPDATE rss_sub_source 
SET sub_url = SUBSTRING(sub_url, 1, CHAR_LENGTH(sub_url) - 1) 
WHERE sub_url LIKE '%/'
limit 10

but shows this error:

SQL Error [42601]: ERROR: syntax error at or near "limit"
  Position: 111

why would this error happen and what should I do to fix it?

asked Jul 22, 2021 at 14:09

Dolphin's user avatar

1

LIMIT isn’t a valid keyword in an UPDATE statement according to the official PostgreSQL documentation:

[ WITH [ RECURSIVE ] with_query [, ...] ]
UPDATE [ ONLY ] table_name [ * ] [ [ AS ] alias ]
    SET { column_name = { expression | DEFAULT } |
          ( column_name [, ...] ) = [ ROW ] ( { expression | DEFAULT } [, ...] ) |
          ( column_name [, ...] ) = ( sub-SELECT )
        } [, ...]
    [ FROM from_item [, ...] ]
    [ WHERE condition | WHERE CURRENT OF cursor_name ]
    [ RETURNING * | output_expression [ [ AS ] output_name ] [, ...] ]

Reference: UPDATE (PostgreSQL Documentation )

Solution

Remove LIMIT 10 from your statement.

a_horse_with_no_name's user avatar

answered Jul 22, 2021 at 14:32

John K. N.'s user avatar

John K. N.John K. N.

15.8k10 gold badges45 silver badges100 bronze badges

0

You could make something like this

But a Limit without an ORDER BY makes no sense, so you must choose one that gets you the correct 10 rows

UPDATE rss_sub_source t1
SET t1.sub_url = SUBSTRING(t1.sub_url, 1, CHAR_LENGTH(t1.sub_url) - 1) 
FROM (SELECT id FROM rss_sub_source WHERE sub_url LIKE '%/' ORDER BY id LIMIT 10) t2 
WHERE t2.id = t1.id

answered Jul 22, 2021 at 14:51

nbk's user avatar

nbknbk

7,7395 gold badges12 silver badges27 bronze badges

So, you’re creating a custom SQL query to perform a task in the database. After putting the code together and running it in PHPmyAdmin it responds with a 1064 error. It may look similar to this:

1064 error message

The 1064 error displays any time you have an issue with your SQL syntax, and is often due to using reserved words, missing data in the database, or mistyped/obsolete commands. So follow along and learn more about what the 1064 error is, some likely causes, and general troubleshooting steps.

Note: Since syntax errors can be hard to locate in long queries, the following online tools can often save time by checking your code and locating issues:

  • PiliApp MySQL Syntax Check
  • EverSQL SQL Query Syntax Check & Validator

Causes for the 1064 error

  • Reserved Words
  • Missing Data
  • Mistyped Commands
  • Obsolete Commands

This may seem cryptic since it is a general error pointing to a syntax issue in the SQL Query statement. Since the 1064 error can have multiple causes, we will go over the most common things that will result in this error and show you how to fix them. Follow along so you can get your SQL queries updated and running successfully.

Using Reserved Words

Every version of MySQL has its own list of reserved words. These are words that are used for specific purposes or to perform specific functions within the MySQL engine. If you attempt to use one of these reserved words, you will receive the 1064 error. For example, below is a short SQL query that uses a reserved word as a table name.

CREATE TABLE alter (first_day DATE, last_day DATE);

How to fix it:

Just because the word alter is reserved does not mean it cannot be used, it just has special requirements to use it as the MySQL engine is trying to call the functionality for the alter command. To fix the issue, you will want to surround the word with backticks, this is usually the button just to the left of the “1” button on the keyboard. The code block below shows how the code will need to look in order to run properly.

CREATE TABLE `alter` (first_day DATE, last_day DATE);

Missing Data

Sometimes data can be missing from the database. This causes issues when the data is required for a query to complete. For example, if a database is built requiring an ID number for every student, it is reasonable to assume a query will be built to pull a student record by that ID number. Such a query would look like this:

SELECT * from students WHERE studentID = $id

If the $id is never properly filled in the code, the query would look like this to the server:

SELECT * from students WHERE studentID =

Since there is nothing there, the MySQL engine gets confused and complains via a 1064 error.

How to fix it:

Hopefully, your application will have some sort of interface that will allow you to bring up the particular record and add the missing data. This is tricky because if the missing data is the unique identifier, it will likely need that information to bring it up, thus resulting in the same error. You can also go into the database (typically within phpMyAdmin) where you can select the particular row from the appropriate table and manually add the data.

Mistyping of Commands

One of the most common causes for the 1064 error is when a SQL statement uses a mistyped command. This is very easy to do and is easily missed when troubleshooting at first. Our example shows an UPDATE command that is accidentally misspelled.

UDPATE table1 SET id = 0;

How to fix it:

Be sure to check your commands prior to running them and ensure they are all spelled correctly.

Below is the syntax for the correct query statement.

UPDATE table1 SET id = 0;

Obsolete Commands

Some commands that were deprecated (slated for removal but still allowed for a period of time) eventually go obsolete. This means that the command is no longer valid in the SQL statement. One of the more common commands is the ‘TYPE‘ command. This has been deprecated since MySQL 4.1 but was finally removed as of version 5.1, where it now gives a syntax error. The ‘TYPE‘ command has been replaced with the ‘ENGINE‘ command. Below is an example of the old version:

CREATE TABLE t (i INT) TYPE = INNODB;

This should be replaced with the new command as below:

CREATE TABLE t (i INT) ENGINE = INNODB;

For developers or sysadmins experienced with the command line, get High-Availability and Root Access for your application, service, and websites with Cloud VPS Hosting.

Error 1064 Summary

As you can see there is more than one cause for the 1064 error within MySQL code. Now, you know how to correct the issues with your SQL Syntax, so your query can run successfully. This list will be updated as more specific instances are reported.

Дата: 25.11.2013

Автор: Василий Лукьянчиков , vl (at) sqlinfo (dot) ru

Статья ориентирована на новичков. В ней объясняется, что означает ошибка сервера MySQL №1064, рассматриваются типичные ситуации и причины возникновения этой ошибки, а также даются рекомендации по исправлению.

Рассмотрим простейший пример.

SELECT mid, time, title, artist, download, view_count, rating, vote_num FROM dle_mservice WHERE category = ‘1’ AND approve = ‘1’ ORDER BY time DESC LIMIT -10,10;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘-10,10’ at line 1

Сервер MySQL сообщает, что в первой строке нашего SQL запроса имеется синтаксическая ошибка, и в одинарных кавычках цитирует часть запроса с того места где начинается ошибка. Это очень полезное свойство, так как позволяет сразу определить место, которое сервер счел ошибочным. В данном случае это ‘-10,10’, ошибка возникает из-за того, что параметр LIMIT не может быть отрицательным числом.

Однако, бывает и так, что цитируемый кусок запроса не содержит синтаксической ошибки. Это означает, что данная часть запроса находится не на своем месте из-за чего весь запрос становится синтаксически неверным. Например, отсутствует разделитель между двумя запросами, пропущен кусок запроса, невидимый символ в дампе и т.д. Неудобством таких ситуаций является то, что сообщение об ошибке не содержит исходный запрос.
Действия по исправлению зависят от контекста возникновения ошибки. Таковых всего 3:

1. Запрос в редакторе.

Самый простейший случай — вы пишите свой запрос в редакторе. Если причина не опечатка, то:

  • Смотреть в документации синтаксис команды для вашей версии сервера MySQL.

    Обратите внимание: речь идет о версии сервера MySQL, а не клиента (phpmyadmin, workbench и т.д.). Версию сервера можно узнать выполнив команду select version();

  • В MySQL допускается использование ключевых слов в качестве имен столбцов/таблиц, но при этом их необходимо заключать в обратные кавычки (там где буква ё на клавиатуре).
    Пример:

    select order from test;
    ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘order from test’ at line 1
    MariaDB [test]> select `order` from test;
    +——-+
    | order |
    +——-+
    |  NULL |
    +——-+

  • По умолчанию ; разделяет команды. Если же нужно выполнить набор из нескольких инструкций как одну команду (например, при создании процедур, фунуций, триггеров), то в зависимости от используемого клиента может потребоваться переопределить разделитель с помощью DELIMITER, иначе интерпретация команды остановится на первой ; и будет ошибка синтаксиса. Пример:

    delimiter //
    create procedure test()
    begin
    set @a=1;
    select @a;
    end//

    Обратите внимание: DELIMITER это команда консольного клиента mysql, необходимость его использования зависит от того как вы передаете команду серверу. Например,:

    • mysql_query() выполняет содержимое как одну команду, добавление delimiter приведет к error 1064 с цитатой, начинающейся со слова delimiter
    • phpmyadmin удаляет слово delimiter из-за чего возникает error 1064 с цитатой, начинающейся с переопределенного разделителя
    • в MysqlQueryBrowser напротив необходимо использовать delimiter.

2. Перенос базы на другой сервер.

У вас есть дамп (т.е. файл с расширением .sql) и при попытке его импортировать вы получаете ошибку 1064. Причины:

  • В различных версиях набор ключевых слов и синтаксис может немного отличаться. Наиболее распространенный случай: команда create table, в которой ключевое слово type было заменено на engine. Например, если вы получаете ошибку:

    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘TYPE=MyISAM CHARACTER SET `utf8`’ at line 29

    Это означает, что вы переносите базу в пятую версию сервера MySQL, в котором ключевое слово TYPE не поддерживается и его нужно заменить на ENGINE.

    Редко бываю случаи, когда перенос идет на старый (~3.23) сервер, который кодировки не поддерживает. Тогда ошибка будет иметь вид:

    #1064 — You have an error in your SQL syntax near ‘DEFAULT CHARACTER SET cp1251 COLLATE cp1251_general_ci’ at line 1

    Такое может произойти, если вы переносите базу с хостинга на локальный комп, где стоит древняя версия MySQL. Лучшим решением в данном случае будет не править дамп, а обновить MySQL.

  • Часто проблемы вызваны тем, что дамп делается неродными средствами MySQL (например, phpmyadmin) из-за чего в нем могут быть BOM-маркер, собственный синтаксис комментариев, завершения команды и т.д. Кроме того при использовании того же phpmyadmin возможна ситуация при которой из-за ограничения апача на размер передаваемого файла команда будет обрезана, что приведет к ошибке 1064.
    Например, если вы получаете ошибку:

    #1064 — You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘
    CREATE TABLE `jos_banner` (
      `bid` int(11) NOT NULL auto_increment,
      `ci‘ at line 1

    Значит ваш дамп содержит BOM-маркер. Это три байта в начале файла, помогающие программе определить что данный файл сохранен в кодировке UTF-8. Проблема в том, что MySQL пытается интерпретировать их как команду из-за чего возникает ошибка синтаксиса. Нужно открыть дамп в текстовом редакторе (например, Notepad++) и сохранить без BOM.

    Для избежания подобных проблем при создании дампа и его импорте лучше пользоваться родными средствами MySQL, см http://sqlinfo.ru/forum/viewtopic.php?id=583

3. Некорректная работа сайта.

Если во время работы сайта появляются ошибки синтаксиса, то, как правило, причина в установке вами сомнительных модулей к вашей cms. Лучшее решение — отказаться от их использования. Еще лучше предварительно проверять их работу на резервной копии.

Пример. Движок dle 7.2, поставили модуль ,вроде бы все Ок, но:

MySQL Error!
————————
The Error returned was:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘AND approve=’1‘ AND date < ‘2008-10-04 04:34:25‘ LIMIT 5’ at line 1

Error Number:
1064
SELECT id, title, date, category, alt_name, flag FROM dle_post WHERE MATCH (title, short_story, full_story, xfields, title) AGAINST (‘Приобретение и оплата скрипта ‘) AND id !=  AND approve=‘1’ AND date < ‘2008-10-04 04:34:25’ LIMIT 5

В данном примере мы видим, что причина ошибки в отсутствии значения после «id != «

Обратите внимание: из процитированного сервером MySQL куска запроса причина ошибки не ясна. Если ваша CMS не показывает весь запрос целиком, то нужно в скриптах найти место где выполняется данный запрос и вывести его на экран командой echo.

Кусок кода, который отвечает за данный запрос это

$db->query («SELECT id, title, date, category, alt_name, flag FROM « . PREFIX . «_post WHERE MATCH (title, short_story, full_story, xfields, title) AGAINST (‘$body’) AND id != «.$row[‘id’].» AND approve=’1′».$where_date.» LIMIT «.$config[‘related_number’]);

Далее можно искать откуда взялась переменная $row и почему в ней нет элемента ‘id’ и вносить исправления, но лучше отказаться от использования такого модуля (неизвестно сколько сюрпризов он еще принесет).

P.S. Если после прочтения статьи ваш вопрос с MySQL Error 1064 остался нерешенным, то задавайте его на форуме SQLinfo

Дата публикации: 25.11.2013

© Все права на данную статью принадлежат порталу SQLInfo.ru. Перепечатка в интернет-изданиях разрешается только с указанием автора и прямой ссылки на оригинальную статью. Перепечатка в бумажных изданиях допускается только с разрешения редакции.

587 votes

1 answers

Get the solution ↓↓↓

Hey I have this error when trying to access my website;
«You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘LIMIT 0, 10’ at line 1»

Line one for me is<?php require_once('Connections/blog.php'); ?>

but it seems the error is coming from here;

$maxRows_getDisplay = 10;
$pageNum_getDisplay = 0;
if (isset($_GET['pageNum_getDisplay'])) {
  $pageNum_getDisplay = $_GET['pageNum_getDisplay'];
}
$startRow_getDisplay = $pageNum_getDisplay * $maxRows_getDisplay;

mysql_select_db($database_blog, $blog);
$query_getDisplay = "SELECT news.title, news.pre,  
 DATE_FORMAT(news.updated, '%M %e, %Y') AS formatted 
 FROM news ORDER BY news.updated DESC LIMIT 2";
$query_limit_getDisplay = sprintf("%s LIMIT %d, %d", 
 $query_getDisplay, $startRow_getDisplay, $maxRows_getDisplay);
$getDisplay = mysql_query($query_limit_getDisplay, $blog) or die(mysql_error());
$row_getDisplay = mysql_fetch_assoc($getDisplay);

If you have any idea, please as I am completely lost.

2022-06-9

Write your answer


558

votes

Answer

Solution:

You have created an SQL statement with two LIMIT clauses, which is not allowed.

This example shows how difficult it is to debug SQL by staring at the code you use to build up a SQL string.

It’s much easier if you can output the final SQL string to debug it.

$query_getDisplay = "SELECT news.title, news.pre,  
 DATE_FORMAT(news.updated, '%M %e, %Y') AS formatted 
 FROM news ORDER BY news.updated DESC LIMIT 2";
$query_limit_getDisplay = sprintf("%s LIMIT %d, %d", 
 $query_getDisplay, $startRow_getDisplay, $maxRows_getDisplay);
error_log("What's wrong with this SQL?  " . $query_limit_getDisplay);
$getDisplay = mysql_query($query_limit_getDisplay, $blog) or die(mysql_error());

You’ll see in your error log:

What's wrong with this SQL?  SELECT news.title, news.pre,  
DATE_FORMAT(news.updated, '%M %e, %Y') AS formatted 
FROM news ORDER BY news.updated DESC LIMIT 2 LIMIT %d, %d

And that makes it much easier to spot invalid SQL syntax (assuming you can recognize valid vs. invalid SQL syntax).


Share solution ↓

Additional Information:

Date the issue was resolved:

2022-06-9

Link To Source

Link To Answer
People are also looking for solutions of the problem: illuminatehttpexceptionsposttoolargeexception

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.


Similar questions

Find the answer in similar questions on our website.

Link24

0 / 0 / 0

Регистрация: 18.04.2013

Сообщений: 111

1

03.10.2013, 20:01. Показов 2918. Ответов 7

Метки нет (Все метки)


Необходима выборка не более 50 значений

SQL
1
2
3
SELECT org, gorod, adres FROM org  WHERE org LIKE %colname% OR adres LIKE  %colname% OR gorod LIKE %colname%  LIMIT 0, 50 UNION  SELECT org2, gorod2, adres2
FROM g2
WHERE org2 LIKE %colname% OR adres2 LIKE  %colname% OR gorod2 LIKE %colname%  LIMIT 0, 50

В чем ошибка? мозг сломал
Всем авансом спасибо!!!

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

03.10.2013, 20:01

Ответы с готовыми решениями:

LIMIT
$result = mysql_query(&quot;SELECT * FROM table_reviews,table_one WHERE table_one.id_image =…

Limit
Есть ли в Accesse что-нибудь подобное Limit из
mySQL?

LIMIT
Есть таблица table с полями (ID_продукта | ID_магазина | цена_продукта)

Можно программно сделать…

LIMIT and WHERE
SELECT id, user, name
FROM classes AS cl
WHERE !del
ORDER BY last DESC
LIMIT {$f}, {$c}…

7

_ViPeR_

610 / 484 / 175

Регистрация: 02.03.2010

Сообщений: 1,220

04.10.2013, 06:13

2

MySQL
1
2
3
4
5
6
7
8
(SELECT org, gorod, adres
FROM org 
WHERE org LIKE %colname% OR adres LIKE  %colname% OR gorod LIKE %colname%)
UNION
(SELECT org2, gorod2, adres2
FROM g2
WHERE org2 LIKE %colname% OR adres2 LIKE  %colname% OR gorod2 LIKE %colname%)
LIMIT 0, 50



0



Link24

0 / 0 / 0

Регистрация: 18.04.2013

Сообщений: 111

04.10.2013, 16:03

 [ТС]

3

Цитата
Сообщение от _ViPeR_
Посмотреть сообщение

MySQL
1
2
3
4
5
6
7
8
(SELECT org, gorod, adres
FROM org 
WHERE org LIKE %colname% OR adres LIKE  %colname% OR gorod LIKE %colname%)
UNION
(SELECT org2, gorod2, adres2
FROM g2
WHERE org2 LIKE %colname% OR adres2 LIKE  %colname% OR gorod2 LIKE %colname%)
LIMIT 0, 50

Дак запрос с select должен начинаться. Так не катит



0



2646 / 1713 / 172

Регистрация: 05.06.2011

Сообщений: 4,913

05.10.2013, 12:04

4

Цитата
Сообщение от Link24
Посмотреть сообщение

В чем ошибка?

Дык текст-то ошибки — где?
Навскидку — а разве строки в кавычки не надо брать? MySQL подзабыл уже.



0



Link24

0 / 0 / 0

Регистрация: 18.04.2013

Сообщений: 111

06.10.2013, 12:27

 [ТС]

5

Цитата
Сообщение от iifat
Посмотреть сообщение

Дык текст-то ошибки — где?
Навскидку — а разве строки в кавычки не надо брать? MySQL подзабыл уже.

SQL
1
2
3
4
5
6
7
8
(SELECT org, gorod, adres
FROM org 
WHERE org LIKE %colname% OR adres LIKE  %colname% OR gorod LIKE %colname%)
UNION
(SELECT org2, gorod2, adres2
FROM g2
WHERE org2 LIKE %colname% OR adres2 LIKE  %colname% OR gorod2 LIKE %colname%)
LIMIT 0, 50

Ошибка — отсутствует SELECT



0



2646 / 1713 / 172

Регистрация: 05.06.2011

Сообщений: 4,913

06.10.2013, 12:43

6

В последнем примере — однозначно. limit — фраза select, одиночно (к оператору в скобках) он не применяется. К исходному select какая ошибка?



0



0 / 0 / 0

Регистрация: 18.04.2013

Сообщений: 111

06.10.2013, 13:07

 [ТС]

7

Цитата
Сообщение от iifat
Посмотреть сообщение

В последнем примере — однозначно. limit — фраза select, одиночно (к оператору в скобках) он не применяется. К исходному select какая ошибка?

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘LIMIT 0, 10’ at line 1



0



_ViPeR_

610 / 484 / 175

Регистрация: 02.03.2010

Сообщений: 1,220

07.10.2013, 06:10

8

Выполнил вот такой запрос у себя

MySQL
1
2
3
4
(SELECT * FROM event WHERE event.typ = 0)
UNION
(SELECT * FROM event WHERE event.typ = 1)
LIMIT 0,10

Никакой ошибки. Не там копаете…



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

07.10.2013, 06:10

Помогаю со студенческими работами здесь

LIMIT в IN
Нужна помощ!
Тут ошибка, как я поняла, в том, что нельзя использовать LIMIT в IN. Как ее обойти? …

update и limit
Здравствуйте!
Был такой запрос:

UPDATE `fruit`
SET `order` = ‘1’
WHERE `user_id` =…

LIMIT с переменными
Приветствую народ.
Что-то я никак не в курю в чем загвоздка.
В общем есть запрос:
CREATE…

Limit и subquery
Имеется таблица T с полями: id, date, price.
Нужно получить выборку, чтобы для каждого id были…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

8

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Lilin ll d6601 ошибка e001
  • Lil solid ошибки
  • Liitokala lii 500 null ошибка
  • Lightshot ошибка загрузки на сервер как исправить
  • Lightshot как изменить толщину линии

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии