ایجاد محدودیت نتایج در پایگاه داده PostgreSQL
استفاده از limit
هنگام اجرای دستور SELECT در PostgreSQL می توانید با استفاده از LIMIT تعداد رکوردها را در نتیجه آن محدود کنید.
در زیر نحو استفاده از LMIT در PostgreSQL آورده شده است:
SELECT column1, column2, columnN
FROM table_name
LIMIT [no of rows]
استفاده از limit در query با پایتون
به عنوان مثال قطعه کد زیر، محتویات جدول به نام EMPLOYEE را بازیابی می کند اما در حالی که تعداد رکوردهای حاصل را به 2 محدود شده است:
import psycopg2
# establishing the connection
conn = psycopg2.connect(
database="mydb", user='postgres', password='password', host='127.0.0.1', port='5432'
)
# Setting auto commit True
conn.autocommit = True
# Creating a cursor object using the cursor() method
cursor = conn.cursor()
# Retrieving single row
sql = '''SELECT * from EMPLOYEE LIMIT 2 OFFSET 2'''
# Executing the query
cursor.execute(sql)
# Fetching the data
result = cursor.fetchall()
print(result)
# Commit your changes in the database
conn.commit()
# Closing the connection
conn.close()
خروجی:
[('Sharukh', 'Sheik', 25, 'M', 8300.0), ('Sarmista', 'Sharma', 26, 'F', 10000.0)]
ثبت دیدگاه
0دیدگاه